import { test, expect } from '@playwright/test';
import { LoginPage } from '../../pages/LoginPage';
import { DashboardPage } from '../../pages/DashboardPage';

test.describe('登录流程', () => {
  let loginPage: LoginPage;
  let dashboardPage: DashboardPage;

  test.beforeEach(async ({ page }) => {
    loginPage = new LoginPage(page);
    dashboardPage = new DashboardPage(page);
    await loginPage.goto();
  });

  test('TC-FE-001: 正常登录成功跳转至仪表盘', async ({ page }) => {
    await loginPage.loginAsAdmin();
    await page.waitForURL('**/dashboard**', { timeout: 10000 });
    await expect(dashboardPage.isDashboardVisible()).resolves.toBe(true);
  });

  test('TC-FE-002: 错误密码显示错误提示', async ({ page }) => {
    await loginPage.login('admin', 'wrongpassword');
    const errorMsg = await loginPage.getErrorMessage();
    expect(errorMsg.length).toBeGreaterThan(0);
  });

  test('TC-FE-003: 空用户名无法提交', async ({ page }) => {
    await loginPage.passwordInput.fill('admin123');
    await loginPage.loginButton.click();
    await expect(page.locator('.ant-form-item-explain-error')).toBeVisible();
  });

  test('TC-FE-004: 登出后返回登录页', async ({ page }) => {
    await loginPage.loginAsAdmin();
    await page.waitForURL('**/dashboard**', { timeout: 10000 });
    await dashboardPage.logout();
    await page.waitForURL('**/login**', { timeout: 10000 });
    await expect(loginPage.usernameInput).toBeVisible();
  });

  test('TC-FE-005: Token过期后自动跳转登录页', async ({ page }) => {
    await loginPage.loginAsAdmin();
    await page.waitForURL('**/dashboard**', { timeout: 10000 });
    await page.evaluate(() => localStorage.removeItem('token'));
    await page.reload();
    await page.waitForURL('**/login**', { timeout: 10000 });
  });
});
