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

test.describe('用户认证 E2E 测试', () => {
  let loginPage: LoginPage;
  let dashboardPage: DashboardPage;

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

  test('成功登录流程', async ({ page }) => {
    await expect(page).toHaveTitle(/登录/);
    
    await loginPage.login('e2e_test_user', 'admin123');
    
    await expect(page).toHaveURL(/.*dashboard/);
    const username = await dashboardPage.getUsername();
    expect(username).toContain('e2e_test_user');
  });

  test('登录失败 - 无效凭证', async ({ page }) => {
    await loginPage.login('invalid', 'invalid');
    
    await page.waitForTimeout(2000);
    
    await expect(page).not.toHaveURL(/.*dashboard/);
    
    const currentUrl = page.url();
    expect(currentUrl).toContain('/login');
  });

  test('登录失败 - 缺少必填字段', async ({ page }) => {
    await loginPage.usernameInput.fill('admin');
    await loginPage.loginButton.click();
    
    const errorMessage = await loginPage.getErrorMessage();
    expect(errorMessage).toBeTruthy();
  });

  test('登出流程', async ({ page }) => {
    await loginPage.login('admin', 'admin123');
    
    await loginPage.logout();
    
    await expect(page).toHaveURL(/.*login/);
    await expect(page).toHaveTitle(/登录/);
  });

  test('登录后可以访问主要菜单', async ({ page }) => {
    await loginPage.login('admin', 'admin123');
    
    await dashboardPage.navigateToUserManagement();
    await expect(page).toHaveURL(/.*users/);
    
    await dashboardPage.navigateToRoleManagement();
    await expect(page).toHaveURL(/.*roles/);
    
    await dashboardPage.navigateToMenuManagement();
    await expect(page).toHaveURL(/.*menus/);
    
    await dashboardPage.navigateToSystemConfig();
    await expect(page).toHaveURL(/.*sysconfig/);
  });
});
