import { test, expect } from '../fixtures/auth.fixture';

/**
 * 用户管理 API 测试
 * 测试用户相关的 CRUD 接口
 */

test.describe('用户管理 API 测试', () => {

  const API_BASE = 'http://localhost:8580';

  // 测试用用户数据
  const testUserData = {
    username: `test_user_${Date.now()}`,
    password: 'Test123456',
    nickname: '测试用户',
    phone: '13800138000',
    email: `test${Date.now()}@example.com`,
  };

  let authToken: string;
  let createdUserId: number;

  test.beforeAll(async ({ loginViaAPI }) => {
    // 登录获取 Token
    const result = await loginViaAPI('platform');
    authToken = result.token;
  });

  test.describe('查询接口', () => {

    test('TC-USER-001: 获取用户列表', async ({ request }) => {
      const response = await request.get(`${API_BASE}/api/users`, {
        headers: {
          Authorization: `Bearer ${authToken}`,
        },
      });

      const data = await response.json();
      expect(data.code).toBe(200);

      console.log('✓ TC-USER-001 通过：获取用户列表');
    });

    test('TC-USER-001: 用户列表分页', async ({ request }) => {
      const response = await request.get(`${API_BASE}/api/users?page=1&pageSize=10`, {
        headers: {
          Authorization: `Bearer ${authToken}`,
        },
      });

      const data = await response.json();
      expect(data.code).toBe(200);

      // 验证分页字段
      expect(data.data).toBeTruthy();
      expect(data.data.records).toBeTruthy();
      expect(Array.isArray(data.data.records)).toBeTruthy();

      console.log('✓ 用户列表分页测试通过');
    });

    test('TC-USER-002: 获取用户详情', async ({ request }) => {
      // 先获取用户列表，取第一个用户
      const listResponse = await request.get(`${API_BASE}/api/users`, {
        headers: { Authorization: `Bearer ${authToken}` },
      });
      const listData = await listResponse.json();

      if (listData.data && listData.data.records && listData.data.records.length > 0) {
        const userId = listData.data.records[0].id;

        const response = await request.get(`${API_BASE}/api/users/${userId}`, {
          headers: { Authorization: `Bearer ${authToken}` },
        });

        const data = await response.json();
        expect(data.code).toBe(200);
        expect(data.data.id).toBe(userId);

        console.log('✓ TC-USER-002 通过：获取用户详情');
      } else {
        console.log('○ 跳过测试：没有用户数据');
      }
    });
  });

  test.describe('创建接口', () => {

    test('TC-USER-003: 创建用户', async ({ request }) => {
      const response = await request.post(`${API_BASE}/api/users`, {
        headers: {
          Authorization: `Bearer ${authToken}`,
          'Content-Type': 'application/json',
        },
        data: testUserData,
      });

      const data = await response.json();

      // 可能成功，也可能因为用户名已存在而失败
      if (data.code === 200) {
        createdUserId = data.data;
        console.log('✓ TC-USER-003 通过：创建用户成功');
      } else {
        console.log('○ 创建用户失败:', data.message);
      }
    });

    test('TC-USER-003: 创建用户 - 必填字段验证', async ({ request }) => {
      const response = await request.post(`${API_BASE}/api/users`, {
        headers: {
          Authorization: `Bearer ${authToken}`,
          'Content-Type': 'application/json',
        },
        data: {
          // 不提供任何字段
        },
      });

      const data = await response.json();
      // 应该返回验证失败
      expect(data.code).not.toBe(200);

      console.log('✓ 创建用户 - 必填字段验证通过');
    });
  });

  test.describe('更新接口', () => {

    test('TC-USER-004: 更新用户', async ({ request }) => {
      // 需要有已存在的用户
      if (!createdUserId) {
        // 尝试获取一个用户
        const listResponse = await request.get(`${API_BASE}/api/users`, {
          headers: { Authorization: `Bearer ${authToken}` },
        });
        const listData = await listResponse.json();

        if (listData.data && listData.data.records && listData.data.records.length > 0) {
          createdUserId = listData.data.records[0].id;
        }
      }

      if (createdUserId) {
        const response = await request.put(`${API_BASE}/api/users/${createdUserId}`, {
          headers: {
            Authorization: `Bearer ${authToken}`,
            'Content-Type': 'application/json',
          },
          data: {
            nickname: '更新后的昵称',
          },
        });

        const data = await response.json();

        if (data.code === 200) {
          console.log('✓ TC-USER-004 通过：更新用户成功');
        } else {
          console.log('○ 更新用户失败:', data.message);
        }
      } else {
        console.log('○ 跳过测试：没有可用用户');
      }
    });
  });

  test.describe('删除接口', () => {

    test('TC-USER-005: 删除用户', async ({ request }) => {
      // 需要有已创建的用户
      if (createdUserId) {
        const response = await request.delete(`${API_BASE}/api/users/${createdUserId}`, {
          headers: {
            Authorization: `Bearer ${authToken}`,
          },
        });

        const data = await response.json();

        if (data.code === 200) {
          console.log('✓ TC-USER-005 通过：删除用户成功');
        } else {
          console.log('○ 删除用户失败:', data.message);
        }
      } else {
        console.log('○ 跳过测试：没有可删除用户');
      }
    });
  });

  test.describe('边界情况', () => {

    test('获取不存在的用户详情', async ({ request }) => {
      const response = await request.get(`${API_BASE}/api/users/999999999`, {
        headers: { Authorization: `Bearer ${authToken}` },
      });

      const data = await response.json();
      // 应该返回用户不存在
      expect(data.code).not.toBe(200);

      console.log('✓ 获取不存在的用户返回正确错误');
    });

    test('无 Token 访问用户接口', async ({ request }) => {
      const response = await request.get(`${API_BASE}/api/users`);

      // 应该返回 401
      expect(response.status()).toBe(401);

      console.log('✓ 无 Token 访问用户接口返回 401');
    });
  });
});
