from __future__ import annotations

import pytest
from playwright.sync_api import Page

from e2e.pages.tenant_auth_page import TenantAuthPage
from e2e.utils.account_store import account_store


@pytest.mark.e2e_auth_closed_loop
@pytest.mark.e2e_ledger
@pytest.mark.e2e_chain
def test_丸友集生成密钥并绑定丸掌柜后完成权限配置闭环(page: Page, settings, bug_reporter) -> None:
    auth_page = TenantAuthPage(page, settings.tenant_home_url, bug_reporter)
    store = account_store()
    permission_pending_account = store.find_permission_pending_binding()
    stored_wanyouji_account = permission_pending_account or store.find_opened_without_binding()
    if stored_wanyouji_account is None:
        pytest.skip(
            "账号台账中没有 wanyouji_status=opened 且可绑定/待配置权限的新企业账号；"
            "请先执行 E2E-SAAS-001 和 E2E-SAAS-003 生成可绑定数据。"
        )
    wanyouji_account = stored_wanyouji_account

    if permission_pending_account:
        auth_key = wanyouji_account.latest_auth_key
        assert auth_key, f"账号 {wanyouji_account.phone} 标记为待配置权限，但台账中没有 latest_auth_key"
    else:
        auth_page.login_main_account(wanyouji_account.phone, wanyouji_account.password)
        bug_reporter.record_if_errors(
            account=wanyouji_account.phone,
            location="丸友集账号-主账号登录",
        )

        auth_key = auth_page.generate_wanyouji_key()
        bug_reporter.record_if_errors(
            account=wanyouji_account.phone,
            location=f"丸友集-企业管理-企业-授权管理-授权密钥-生成密钥：{auth_key}",
        )

        auth_page.login_main_account(settings.wanzhanggui_tenant_phone, settings.wanzhanggui_tenant_password)
        bug_reporter.record_if_errors(
            account=settings.wanzhanggui_tenant_phone,
            location="丸掌柜账号-主账号登录",
        )

        auth_page.activate_key_for_wanzhanggui(auth_key)
        store.mark_wanzhanggui_permission_pending(
            wanyouji_account,
            auth_key,
            bound_enterprise=settings.wanzhanggui_tenant_phone,
        )
        bug_reporter.record_if_errors(
            account=settings.wanzhanggui_tenant_phone,
            location=f"丸掌柜-企业管理-企业-授权管理-我的授权-选择丸掌柜并激活密钥：{auth_key}",
        )

    auth_page.login_main_account(wanyouji_account.phone, wanyouji_account.password)
    auth_page.verify_and_save_wanyouji_permissions(auth_key)
    bug_reporter.record_if_errors(
        account=wanyouji_account.phone,
        location=f"丸友集-企业管理-企业-授权管理-授权密钥-管理授权-验证福通互通并保存：{auth_key}",
    )

    auth_page.login_main_account(settings.wanzhanggui_tenant_phone, settings.wanzhanggui_tenant_password)
    auth_page.verify_wanzhanggui_authorized_permissions(auth_key, ["创建订单"])
    bug_reporter.record_if_errors(
        account=settings.wanzhanggui_tenant_phone,
        location=f"丸掌柜-企业管理-企业-授权管理-我的授权-查看授权详情-验证创建订单权限：{auth_key}",
    )
    store.mark_wanzhanggui_bound(wanyouji_account, auth_key, bound_enterprise=settings.wanzhanggui_tenant_phone)
