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

/**
 * 租户管理 API 测试
 * 测试租户相关的接口（超管专用）
 */

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

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

  test.beforeAll(async ({ loginViaAPI }) => {
    // 使用超管账号登录
    const result = await loginViaAPI('platform');
    authToken = result.token;
  });

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

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

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

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

    test('获取租户列表 - 分页参数', async ({ request }) => {
      const response = await request.get(`${API_BASE}/api/tenants?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(data.data.total).toBeDefined();

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

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

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

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

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

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

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

    test('TC-TENANT-003: 创建租户', async ({ request }) => {
      const tenantCode = `test_tenant_${Date.now()}`;

      const response = await request.post(`${API_BASE}/api/tenants`, {
        headers: {
          Authorization: `Bearer ${authToken}`,
          'Content-Type': 'application/json',
        },
        data: {
          code: tenantCode,
          name: `测试租户${Date.now()}`,
          status: 1,
        },
      });

      const data = await response.json();

      if (data.code === 200) {
        console.log('✓ TC-TENANT-003 通过：创建租户成功');
      } else {
        console.log('○ 创建租户失败:', data.message);
      }
    });

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

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

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

    test('创建租户 - 编码重复验证', async ({ request }) => {
      const response = await request.post(`${API_BASE}/api/tenants`, {
        headers: {
          Authorization: `Bearer ${authToken}`,
          'Content-Type': 'application/json',
        },
        data: {
          code: 'platform', // 已存在的编码
          name: '重复测试租户',
          status: 1,
        },
      });

      const data = await response.json();
      // 应该返回编码已存在
      expect(data.code).not.toBe(200);
      expect(data.message).toContain('已存在');

      console.log('✓ 创建租户 - 编码重复验证通过');
    });
  });

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

    test('TC-TENANT-004: 更新租户', async ({ request }) => {
      // 先获取租户列表
      const listResponse = await request.get(`${API_BASE}/api/tenants`, {
        headers: { Authorization: `Bearer ${authToken}` },
      });
      const listData = await listResponse.json();

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

        const response = await request.put(`${API_BASE}/api/tenants/${tenantId}`, {
          headers: {
            Authorization: `Bearer ${authToken}`,
            'Content-Type': 'application/json',
          },
          data: {
            name: '更新后的租户名称',
          },
        });

        const data = await response.json();

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

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

    test('删除租户', async ({ request }) => {
      // 先创建一个测试租户
      const createResponse = await request.post(`${API_BASE}/api/tenants`, {
        headers: {
          Authorization: `Bearer ${authToken}`,
          'Content-Type': 'application/json',
        },
        data: {
          code: `test_del_${Date.now()}`,
          name: '待删除测试租户',
          status: 1,
        },
      });
      const createData = await createResponse.json();

      if (createData.code === 200 && createData.data) {
        const tenantId = createData.data;

        // 删除租户
        const deleteResponse = await request.delete(`${API_BASE}/api/tenants/${tenantId}`, {
          headers: {
            Authorization: `Bearer ${authToken}`,
          },
        });

        const data = await deleteResponse.json();

        if (data.code === 200) {
          console.log('✓ 删除租户成功');
        } else {
          console.log('○ 删除租户失败:', data.message);
        }
      } else {
        console.log('○ 跳过测试：创建测试租户失败');
      }
    });
  });

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

    test('非超管访问租户管理接口', async ({ request, loginViaAPI }) => {
      // 使用普通租户账号登录
      const { token } = await loginViaAPI('gdlib');

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

      // 应该返回无权限或空列表
      const data = await response.json();
      console.log('非超管访问租户列表响应:', data);

      console.log('✓ 非超管访问租户管理接口测试完成');
    });

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

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

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