from __future__ import annotations

import pytest
from playwright.sync_api import Page

from e2e.pages.admin_page import AdminPage
from e2e.pages.tenant_registration_page import AccountAlreadyRegistered, TenantRegistrationPage
from e2e.utils.account_store import account_store
from e2e.utils.data_factory import enterprise_data
from e2e.utils.image_captcha import ImageCaptchaSolver
from e2e.utils.verification_code import FeishuConfig, VerificationCodeProvider


@pytest.mark.e2e_saas_001
@pytest.mark.e2e_seed
@pytest.mark.e2e_standalone
def test_租户注册企业并由主站完成商户认证(page: Page, settings, bug_reporter) -> None:
    code_provider = VerificationCodeProvider(
        mode=settings.verification_code_mode,
        static_code=settings.verification_code_static,
        feishu_config=FeishuConfig(
            app_id=settings.feishu_app_id,
            app_secret=settings.feishu_app_secret,
            chat_id=settings.feishu_chat_id,
            timeout_seconds=settings.feishu_timeout_seconds,
            poll_interval_seconds=settings.feishu_poll_interval_seconds,
        ),
        manual_code_file=settings.manual_code_file,
        manual_timeout_seconds=settings.manual_code_timeout_seconds,
        manual_poll_interval_seconds=settings.manual_code_poll_interval_seconds,
    )
    image_captcha_solver = ImageCaptchaSolver(mode=settings.image_captcha_mode)
    tenant = TenantRegistrationPage(page, settings.tenant_home_url, code_provider, image_captcha_solver, bug_reporter)
    admin = AdminPage(page, settings.admin_url)

    registered = None
    for _ in range(settings.max_register_attempts):
        candidate = enterprise_data(
            password=settings.register_password,
            prefix=settings.phone_prefix,
            enterprise_prefix=settings.enterprise_name_prefix,
        )
        try:
            tenant.register_enterprise(candidate)
            registered = candidate
            break
        except AccountAlreadyRegistered:
            tenant.logout_if_needed()
            continue

    assert registered is not None, "随机手机号均已注册，未能完成企业注册"

    bug_reporter.clear()
    admin.login(settings.admin_username, settings.admin_password)
    bug_reporter.record_if_errors(account=settings.admin_username, location="SaaS主站-登录")
    admin.approve_enterprise_certification(registered.contact_name)
    bug_reporter.record_if_errors(account=settings.admin_username, location="SaaS主站-商户认证审核")
    account_store().mark_certified(registered)

    tenant.login(registered.phone, registered.password)
    assert tenant.certification_passed_visible(registered.enterprise_name), f"企业 {registered.enterprise_name} 未在租户端展示认证通过状态"
