"""管理端登录测试用例。

标记:
    pytest -m admin            # 仅管理端用例
    pytest -m p0               # P0 冒烟
    pytest -m smoke            # 冒烟
"""

import pytest
from playwright.sync_api import Page

pytestmark = [pytest.mark.admin]


class TestAdminSmoke:
    """管理端冒烟 — 验证预登录态。"""

    @pytest.mark.p0
    @pytest.mark.smoke
    def test_admin_access_with_saved_auth(self, page: Page, admin_config, ensure_login):
        """验证预登录态可直接访问管理后台。"""
        ensure_login("super_admin")
        page.goto(admin_config["base_url"])
        page.wait_for_timeout(2000)
        assert "#/login" not in page.url and "/login" not in page.url, (
            "预登录态失效！请运行: python tests/web/admin/save_auth.py"
        )

    @pytest.mark.p0
    @pytest.mark.smoke
    def test_team_leader_access(self, page: Page, admin_config, ensure_login):
        """验证车队长预登录态有效。"""
        ensure_login("team_leader")
        page.goto(admin_config["base_url"])
        page.wait_for_timeout(2000)
        assert "#/login" not in page.url and "/login" not in page.url

    @pytest.mark.p0
    @pytest.mark.smoke
    def test_dashboard_loads(self, page: Page, admin_config, ensure_login):
        """验证首页可正常加载。"""
        ensure_login("super_admin")
        page.goto(admin_config["base_url"])
        assert page.title(), "首页应显示页面标题"


class TestLoginPage:
    """登录页交互验证。"""

    @pytest.mark.p1
    def test_login_page_accessible(self, page: Page, admin_config):
        """验证登录页可正常访问。"""
        page.goto(f"{admin_config['base_url']}/#/login")
        assert page.get_by_placeholder("请输入用户名").is_visible()

    @pytest.mark.p1
    def test_login_page_elements(self, page: Page, admin_config):
        """验证登录页元素完整。"""
        page.goto(f"{admin_config['base_url']}/#/login")
        assert page.get_by_placeholder("请输入用户名").is_visible()
        assert page.get_by_placeholder("请输入密码").is_visible()
        assert page.get_by_role("button", name="登录").is_visible()

    @pytest.mark.p1
    def test_session_redirect(self, page: Page, admin_config, ensure_login):
        """验证已登录用户访问登录页被重定向。"""
        ensure_login("super_admin")
        page.goto(admin_config["base_url"])
        page.wait_for_timeout(2000)
        assert "#/login" not in page.url

        page.goto(f"{admin_config['base_url']}/#/login")
        page.wait_for_timeout(2000)
        assert "#/login" not in page.url and "/login" not in page.url
