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

/**
 * 角色权限 API 测试
 * 测试角色、权限、菜单相关的接口
 */

test.describe('角色权限 API 测试', () => {

  const API_BASE = 'http://localhost:8580';
  let authToken: string;

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

  test.describe('角色管理接口', () => {

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

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

      console.log('✓ TC-ROLE-001 通过：获取角色列表');
    });

    test('获取角色详情', async ({ request }) => {
      // 先获取角色列表
      const listResponse = await request.get(`${API_BASE}/api/roles`, {
        headers: { Authorization: `Bearer ${authToken}` },
      });
      const listData = await listResponse.json();

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

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

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

        console.log('✓ 获取角色详情通过');
      } else {
        console.log('○ 跳过测试：没有角色数据');
      }
    });

    test('创建角色 - 必填字段验证', async ({ request }) => {
      const response = await request.post(`${API_BASE}/api/roles`, {
        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-ROLE-002: 获取权限列表', async ({ request }) => {
      const response = await request.get(`${API_BASE}/api/permissions`, {
        headers: {
          Authorization: `Bearer ${authToken}`,
        },
      });

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

      console.log('✓ TC-ROLE-002 通过：获取权限列表');
    });

    test('获取权限树', async ({ request }) => {
      const response = await request.get(`${API_BASE}/api/permissions/tree`, {
        headers: { Authorization: `Bearer ${authToken}` },
      });

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

      console.log('✓ 获取权限树通过');
    });
  });

  test.describe('菜单管理接口', () => {

    test('TC-ROLE-003: 获取菜单树', async ({ request }) => {
      const response = await request.get(`${API_BASE}/api/menus`, {
        headers: {
          Authorization: `Bearer ${authToken}`,
        },
      });

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

      // 验证返回的是树形结构
      expect(Array.isArray(data.data)).toBeTruthy();

      console.log('✓ TC-ROLE-003 通过：获取菜单树');
    });

    test('菜单包含正确的字段', async ({ request }) => {
      const response = await request.get(`${API_BASE}/api/menus`, {
        headers: { Authorization: `Bearer ${authToken}` },
      });

      const data = await response.json();

      if (data.data && data.data.length > 0) {
        const menu = data.data[0];
        expect(menu.id).toBeTruthy();
        expect(menu.name).toBeTruthy();
        expect(menu.path).toBeTruthy();
        expect(menu.component).toBeTruthy();

        console.log('✓ 菜单包含正确的字段');
      }
    });
  });

  test.describe('用户角色关联', () => {

    test('给用户分配角色', async ({ request }) => {
      // 获取第一个用户和第一个角色
      const [userList, roleList] = await Promise.all([
        request.get(`${API_BASE}/api/users`, {
          headers: { Authorization: `Bearer ${authToken}` },
        }).then(r => r.json()),
        request.get(`${API_BASE}/api/roles`, {
          headers: { Authorization: `Bearer ${authToken}` },
        }).then(r => r.json()),
      ]);

      if (userList.data?.records?.length > 0 && roleList.data?.records?.length > 0) {
        const userId = userList.data.records[0].id;
        const roleId = roleList.data.records[0].id;

        const response = await request.post(`${API_BASE}/api/users/${userId}/roles`, {
          headers: {
            Authorization: `Bearer ${authToken}`,
            'Content-Type': 'application/json',
          },
          data: {
            roleIds: [roleId],
          },
        });

        const data = await response.json();
        console.log('分配角色响应:', data);

        console.log('✓ 给用户分配角色测试完成');
      } else {
        console.log('○ 跳过测试：没有用户或角色数据');
      }
    });
  });
});
