from __future__ import annotations

import pytest
from playwright.sync_api import Page

from e2e.pages.wanzhanggui_push_page import WanzhangguiPushPage
from e2e.utils.account_store import account_store


@pytest.mark.e2e_push_001
@pytest.mark.e2e_ledger
@pytest.mark.e2e_chain
def test_丸掌柜新增丸友集工作室授权(page: Page, settings, bug_reporter) -> None:
    wanzhanggui_phone = "19147509308"
    wanzhanggui_password = "test123456"
    store = account_store()

    wanzhanggui_account = store.find(phone=wanzhanggui_phone)
    assert wanzhanggui_account is not None, f"台账中未找到丸掌柜账号 {wanzhanggui_phone}"
    assert wanzhanggui_account.wanzhanggui_status == "opened", (
        f"账号 {wanzhanggui_phone} 未处于已开通丸掌柜状态，当前状态：{wanzhanggui_account.wanzhanggui_status}"
    )

    wanyouji_account = store.find_bound_wanyouji_without_workshop_authorization(wanzhanggui_phone)
    if wanyouji_account is None:
        pytest.skip(f"没有已绑定 {wanzhanggui_phone} 且未新增工作室授权的丸友集账号")

    push_page = WanzhangguiPushPage(page, settings.tenant_home_url, bug_reporter)
    push_page.login_main_account(wanzhanggui_phone, wanzhanggui_password)
    bug_reporter.record_if_errors(
        account=wanzhanggui_phone,
        location="丸掌柜账号-主账号登录",
    )

    push_page.add_wanyouji_workshop_authorization(wanyouji_account.enterprise_name)
    bug_reporter.record_if_errors(
        account=wanzhanggui_phone,
        location=f"丸掌柜-履约工作室/平台-工作室授权-新增丸友集工作室：{wanyouji_account.enterprise_name}",
    )

    binding = next(
        (
            item
            for item in wanyouji_account.wanzhanggui_bindings
            if item.get("phone") == wanzhanggui_phone
        ),
        {},
    )
    store.mark_workshop_authorized(
        wanyouji_account,
        wanzhanggui_phone,
        auth_key=binding.get("auth_key", ""),
    )
