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

test.describe('调试测试 - 网络请求监控', () => {
  let loginPage: LoginPage;
  let dashboardPage: DashboardPage;
  let userManagementPage: UserManagementPage;

  test.beforeEach(async ({ page }) => {
    loginPage = new LoginPage(page);
    dashboardPage = new DashboardPage(page);
    userManagementPage = new UserManagementPage(page);
    
    // 监控所有网络请求
    page.on('request', request => {
      console.log(`>> REQUEST: ${request.method()} ${request.url()}`);
      if (request.method() === 'POST' || request.method() === 'PUT') {
        console.log(`   POST DATA: ${request.postData()}`);
      }
    });
    
    page.on('response', response => {
      console.log(`<< RESPONSE: ${response.status()} ${response.url()}`);
      if (response.status() >= 400) {
        console.log(`   ❌ ERROR RESPONSE: ${response.status()} ${response.url()}`);
      }
    });
    
    // 清理localStorage
    await page.goto('/');
    await page.evaluate(() => localStorage.clear());
    
    // 重新登录
    await loginPage.goto();
    await loginPage.login('e2e_test_user', 'admin123');
  });

  test('创建用户 - 带网络监控', async ({ page }) => {
    console.log('\n========== 开始创建用户测试 ==========\n');
    
    await dashboardPage.navigateToUserManagement();
    console.log('✅ 导航到用户管理页面');
    
    await userManagementPage.clickCreateUser();
    console.log('✅ 点击创建用户按钮');
    
    const timestamp = Date.now();
    const userData = {
      username: `testuser_${timestamp}`,
      nickname: `测试用户${timestamp}`,
      email: `test_${timestamp}@example.com`,
      phone: '13800138000',
      password: 'Test123!@#',
      confirmPassword: 'Test123!@#',
    };
    
    console.log(`📝 填写用户数据: ${JSON.stringify(userData)}`);
    await userManagementPage.fillUserForm(userData);
    console.log('✅ 填写用户表单完成');
    
    console.log('📤 准备提交表单...');
    await userManagementPage.submitForm();
    console.log('✅ 表单已提交');
    
    // 等待一段时间，观察网络请求
    await page.waitForTimeout(5000);
    
    console.log('\n========== 测试结束 ==========\n');
  });
});
