from __future__ import annotations

from datetime import datetime

import pytest
from playwright.sync_api import Page

from e2e.pages.saas_subscription_admin_page import SaasSubscriptionAdminPage
from e2e.utils.product_solution_runtime import record_versioned_app_for_product_pack


@pytest.mark.e2e_standalone
def test_appver_flow_001_create_app_version_and_read_back(page: Page, settings, bug_reporter) -> None:
    version_name = f"自动化版本_{datetime.now().strftime('%Y%m%d%H%M%S')}"
    version_description = "自动化新增应用版本"

    admin = SaasSubscriptionAdminPage(page, settings.admin_url)
    admin.login(settings.admin_username, settings.admin_password)
    bug_reporter.record_if_errors(account=settings.admin_username, location="SaaS Admin 登录")

    app_code, resource_name = admin.find_visible_app_with_bindable_version_resource(max_rows=20)

    admin.create_app_version(version_name, version_description)
    admin.assert_version_visible(version_name)
    bug_reporter.record_if_errors(
        account=settings.admin_username,
        location=f"APPVER-FLOW-001 选择有资源应用并新增版本：{app_code}/{version_name}/{resource_name}",
    )

    admin.select_app_version(version_name)
    admin.search_version_resource(resource_name)
    admin.select_all_filtered_version_resources()
    admin.save_current_version_resources()
    admin.assert_version_resource_checked(resource_name, checked=True)
    bug_reporter.record_if_errors(
        account=settings.admin_username,
        location=f"APPVER-FLOW-004 新增版本后立即绑定资源：{app_code}/{version_name}/{resource_name}",
    )
    admin.assert_operation_log(
        target_type="应用",
        target_code=app_code,
        operation_info="新建应用版本",
    )
    admin.assert_operation_log(
        target_type="应用",
        target_code=app_code,
        operation_info="保存应用版本菜单",
    )
    record_versioned_app_for_product_pack(
        app_code=app_code,
        version_name=version_name,
        resource_name=resource_name,
    )
    bug_reporter.record_if_errors(
        account=settings.admin_username,
        location=f"APPVER-FLOW-001+004 完整应用版本产物已记录：{app_code}/{version_name}/{resource_name}",
    )
