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_003
@pytest.mark.e2e_ledger
@pytest.mark.e2e_standalone
def test_已认证商户申请开通丸友集并由主站审批(page: Page, settings, bug_reporter) -> None:
    tenant_login = 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 = TenantSubscriptionPage(page, settings.tenant_home_url, tenant_login, bug_reporter)
    admin = AdminApplicationPage(page, settings.admin_url)
    store = account_store()
    stored_account = store.find_certified_without_wanyouji()
    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.login_certified_tenant(account.phone, account.password)
    bug_reporter.record_if_errors(
        account=account.phone,
        location="租户平台-已认证账号登录",
    )

    tenant.apply_wanyouji(account.phone)
    bug_reporter.record_if_errors(
        account=account.phone,
        location="租户平台-订阅购买-丸友集申请开通",
    )

    admin.login(settings.admin_username, settings.admin_password)
    bug_reporter.record_if_errors(account=settings.admin_username, location="SaaS主站-登录")
    admin.approve_product_application(
        account.enterprise_name,
        "丸友集",
        merchant_id=account.merchant_id,
        product_id=settings.wanyouji_product_id,
    )
    bug_reporter.record_if_errors(account=settings.admin_username, location="SaaS主站-丸友集应用开通审批")

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