import { test, expect } from '../../utils/test-setup';
import { readFileSync } from 'fs';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const testUsers = JSON.parse(readFileSync(join(__dirname, '../../fixtures/test-users.json'), 'utf-8'));

test.describe.serial('用户管理 E2E 测试', () => {
  test.beforeEach(async ({ adminLoginPage, userManagementPage }) => {
    // 以管理员身份登录后台
    await adminLoginPage.goto();
    await adminLoginPage.login(testUsers.admin.username, testUsers.admin.password);
    await userManagementPage.goto();
  });

  test('查看用户列表', async ({ userManagementPage }) => {
    await userManagementPage.expectToBeVisible();
    const userCount = await userManagementPage.getUserCount();
    expect(userCount).toBeGreaterThan(0);
  });

  test('搜索用户', async ({ userManagementPage }) => {
    await userManagementPage.searchUsers('admin');
    const userCount = await userManagementPage.getUserCount();
    expect(userCount).toBeGreaterThan(0);

    // 验证搜索结果包含admin用户
    const adminUser = await userManagementPage.getUserByUsername('admin');
    expect(adminUser).not.toBeNull();
  });

  test('创建新用户', async ({ userManagementPage }) => {
    const testUsername = `testuser_${Date.now()}`;
    const testPassword = 'Test123!@#';

    await userManagementPage.createUser({
      username: testUsername,
      password: testPassword,
      nickname: '测试用户',
      email: `${testUsername}@example.com`,
      phone: '13800138000',
      name: '测试用户'
    });

    // 验证用户创建成功
    await userManagementPage.expectUserExists(testUsername);
  });

  test('编辑用户信息', async ({ userManagementPage }) => {
    const testUsername = `edituser_${Date.now()}`;
    const testPassword = 'Test123!@#';

    // 先创建测试用户
    await userManagementPage.createUser({
      username: testUsername,
      password: testPassword,
      nickname: '原始昵称',
      email: `${testUsername}@example.com`
    });

    // 编辑用户信息
    await userManagementPage.editUser(testUsername, {
      nickname: '更新后的昵称',
      email: `updated_${testUsername}@example.com`,
      phone: '13900139000',
      name: '更新姓名'
    });

    // 验证用户信息已更新
    const userRow = await userManagementPage.getUserByUsername(testUsername);
    expect(userRow).not.toBeNull();
    await expect(userRow!).toContainText('更新后的昵称');
    await expect(userRow!).toContainText(`updated_${testUsername}@example.com`);
  });

  test('删除用户', async ({ userManagementPage }) => {
    const testUsername = `deleteuser_${Date.now()}`;
    const testPassword = 'Test123!@#';

    // 先创建测试用户
    await userManagementPage.createUser({
      username: testUsername,
      password: testPassword,
      nickname: '待删除用户',
      email: `${testUsername}@example.com`
    });

    // 验证用户存在
    await userManagementPage.expectUserExists(testUsername);

    // 删除用户
    await userManagementPage.deleteUser(testUsername);

    // 验证用户已被删除
    await userManagementPage.expectUserNotExists(testUsername);
  });

  test('用户分页功能', async ({ userManagementPage }) => {
    // 确保有足够多的用户来测试分页
    const initialCount = await userManagementPage.getUserCount();

    if (initialCount < 10) {
      // 创建一些测试用户
      for (let i = 0; i < 5; i++) {
        await userManagementPage.createUser({
          username: `pagetest_${Date.now()}_${i}`,
          password: 'Test123!@#',
          nickname: `分页测试用户 ${i}`
        });
      }
    }

    // 搜索并验证分页控件可见
    await userManagementPage.searchUsers('');
    await expect(userManagementPage.pagination).toBeVisible();
  });

  test('创建用户验证 - 用户名已存在', async ({ userManagementPage }) => {
    // 尝试创建已存在的用户
    await userManagementPage.createUser({
      username: 'admin',
      password: 'Test123!@#',
      nickname: '重复用户'
    });

    // 应该显示错误消息
    await expect(userManagementPage.page.locator('text=创建失败')).toBeVisible();
  });

  test('响应式布局 - 桌面端', async ({ userManagementPage, page }) => {
    await page.setViewportSize({ width: 1200, height: 800 });
    await userManagementPage.expectToBeVisible();

    // 验证桌面端布局元素
    await expect(userManagementPage.searchInput).toBeVisible();
    await expect(userManagementPage.createUserButton).toBeVisible();
    await expect(userManagementPage.userTable).toBeVisible();
  });

  test('响应式布局 - 移动端', async ({ userManagementPage, page }) => {
    await page.setViewportSize({ width: 375, height: 667 });
    await userManagementPage.expectToBeVisible();

    // 验证移动端布局
    await expect(userManagementPage.pageTitle).toBeVisible();
    await expect(userManagementPage.searchInput).toBeVisible();
  });

  test('完整用户管理工作流 - 登录→创建→编辑→删除', async ({ adminLoginPage, userManagementPage, page }) => {
    const testUsername = `workflow_${Date.now()}`;
    const testPassword = 'Test123!@#';

    // 1. 登录系统
    await adminLoginPage.goto();
    await adminLoginPage.login(testUsers.admin.username, testUsers.admin.password);

    // 验证登录成功，跳转到Dashboard
    await expect(page).toHaveURL(/.*dashboard/);
    await expect(page.locator('text=仪表盘')).toBeVisible();

    // 2. 导航到用户管理页面
    await userManagementPage.goto();
    await userManagementPage.expectToBeVisible();

    // 3. 创建新用户
    await userManagementPage.createUser({
      username: testUsername,
      password: testPassword,
      nickname: '工作流测试用户',
      email: `${testUsername}@example.com`,
      phone: '13800138000',
      name: '工作流测试'
    });

    // 验证用户创建成功
    await userManagementPage.expectUserExists(testUsername);

    // 4. 搜索并编辑用户
    await userManagementPage.searchUsers(testUsername);
    await userManagementPage.editUser(testUsername, {
      nickname: '更新后的工作流用户',
      email: `updated_${testUsername}@example.com`,
      phone: '13900139000',
      name: '更新工作流测试'
    });

    // 验证用户信息已更新
    const userRow = await userManagementPage.getUserByUsername(testUsername);
    await expect(userRow).toBeVisible();
    await expect(userRow).toContainText('更新后的工作流用户');
    await expect(userRow).toContainText(`updated_${testUsername}@example.com`);

    // 5. 删除用户
    await userManagementPage.deleteUser(testUsername);

    // 验证用户已被删除
    await userManagementPage.expectUserNotExists(testUsername);

    // 6. 返回Dashboard验证状态
    await page.goto('/admin/dashboard');
    await expect(page.locator('text=仪表盘')).toBeVisible();
    await expect(page.locator('text=欢迎回来')).toBeVisible();
  });

  test('边界条件测试 - 批量操作和错误处理', async ({ userManagementPage }) => {
    // 测试空搜索
    await userManagementPage.searchUsers('nonexistentuser12345');
    const emptyCount = await userManagementPage.getUserCount();
    expect(emptyCount).toBe(0);

    // 验证空状态提示 - 检查用户计数为0
    await expect(userManagementPage.page.locator('text=共 0 位用户')).toBeVisible();

    // 测试特殊字符搜索
    await userManagementPage.searchUsers('@#$%');
    const specialCharCount = await userManagementPage.getUserCount();
    expect(specialCharCount).toBe(0);

    // 清除搜索
    await userManagementPage.searchUsers('');
    const normalCount = await userManagementPage.getUserCount();
    expect(normalCount).toBeGreaterThan(0);
  });
});