from __future__ import annotations

import pytest
from playwright.sync_api import Page

from e2e.pages.admin_application_page import AdminApplicationPage
from e2e.pages.tenant_registration_page import TenantRegistrationPage
from e2e.pages.tenant_subscription_page import TenantSubscriptionPage
from e2e.utils.account_store import E2EAccount, account_store
from e2e.utils.image_captcha import ImageCaptchaSolver
from e2e.utils.verification_code import VerificationCodeProvider


@pytest.mark.e2e_saas_004
@pytest.mark.e2e_ledger
@pytest.mark.e2e_standalone
def test_已认证商户申请开通丸掌柜并由主站审批(page: Page, settings, bug_reporter) -> None:
    tenant_registration = TenantRegistrationPage(
        page=page,
        home_url=settings.tenant_home_url,
        code_provider=VerificationCodeProvider(mode="manual"),
        image_captcha_solver=ImageCaptchaSolver(mode=settings.image_captcha_mode),
        bug_reporter=bug_reporter,
    )
    tenant_subscription = TenantSubscriptionPage(
        page,
        settings.tenant_home_url,
        tenant_registration,
        bug_reporter,
    )
    admin_application = AdminApplicationPage(page, settings.admin_url)
    store = account_store()
    stored_account = store.find_certified_without_wanzhanggui()
    account = stored_account or E2EAccount(
        phone=settings.certified_tenant_phone,
        password=settings.certified_tenant_password,
        enterprise_name=settings.certified_tenant_enterprise_name,
        contact_name="",
        certification_status="approved",
        merchant_id=settings.certified_tenant_merchant_id,
    )

    tenant_subscription.login_certified_tenant(account.phone, account.password)
    bug_reporter.record_if_errors(account=account.phone, location="租户平台-已认证账号登录")
    tenant_subscription.apply_wanzhanggui(account.phone)
    if stored_account:
        account = store.mark_wanzhanggui_pending(account)
    bug_reporter.record_if_errors(account=account.phone, location="租户平台-订阅购买-丸掌柜申请开通")

    admin_application.login(settings.admin_username, settings.admin_password)
    bug_reporter.record_if_errors(account=settings.admin_username, location="SaaS主站-登录")
    admin_application.approve_product_application(
        account.enterprise_name,
        "丸掌柜",
        merchant_id=account.merchant_id,
        product_id=settings.wanzhanggui_product_id,
    )
    bug_reporter.record_if_errors(account=settings.admin_username, location="SaaS主站-丸掌柜应用开通审批")

    tenant_subscription.login_certified_tenant(account.phone, account.password)
    assert tenant_subscription.wanzhanggui_available(), "主站审批通过后，租户订阅购买页未展示丸掌柜已开通或可进入状态"
    if stored_account:
        store.mark_wanzhanggui_opened(account)
