/**
 * IAM 后台 - DataScope CRUD 集成测试
 */
import { INestApplication } from '@nestjs/common';
import request from 'supertest';
import { PrismaService } from '@/core/database/prisma/prisma.service';
import { cleanupDatabase } from '../../helpers/cleanup.helper';
import { createTestApp } from '../../helpers/app.helper';
import { setupIntegrationTest } from '../../helpers/test-setup.helper';

describe('IAM Admin - DataScopes API', () => {
  let app: INestApplication;
  let prisma: PrismaService;
  let adminToken: string;

  beforeAll(async () => {
    app = await createTestApp();
    prisma = app.get<PrismaService>(PrismaService);
  });

  beforeEach(async () => {
    const ctx = await setupIntegrationTest(app, prisma);
    adminToken = ctx.adminToken;
  });

  afterEach(async () => {
    await cleanupDatabase(prisma);
  });

  afterAll(async () => {
    await app.close();
  });

  it('[IAM-ADMIN-DS-001] GET /iam/data-scopes 返回内置 DataScope 列表', async () => {
    const res = await request(app.getHttpServer())
      .get('/api/v1/iam/data-scopes')
      .set('Authorization', `Bearer ${adminToken}`)
      .expect(200);

    expect(Array.isArray(res.body.data)).toBe(true);
    expect(res.body.data.length).toBeGreaterThan(0);
    expect(res.body.data[0]).toHaveProperty('code');
    expect(res.body.data[0]).toHaveProperty('scopeType');
  });

  it('[IAM-ADMIN-DS-002] POST 创建自定义 DataScope，落审计', async () => {
    const code = `TEST_SCOPE_${Date.now()}`;
    const res = await request(app.getHttpServer())
      .post('/api/v1/iam/data-scopes')
      .set('Authorization', `Bearer ${adminToken}`)
      .send({ code, name: '测试 scope', scopeType: 'ORGANIZATION' })
      .expect(201);

    expect(res.body.data.code).toBe(code);
    expect(res.body.data.isBuiltIn).toBe(false);

    const audits = await prisma.iamAuditLog.findMany({
      where: { resource: 'DataScope', action: 'CREATE', targetId: res.body.data.id },
    });
    expect(audits.length).toBe(1);
  });

  it('[IAM-ADMIN-DS-003] CUSTOM scopeType 创建被拒（永久禁用）', async () => {
    await request(app.getHttpServer())
      .post('/api/v1/iam/data-scopes')
      .set('Authorization', `Bearer ${adminToken}`)
      .send({ code: `BAD_${Date.now()}`, name: 'x', scopeType: 'CUSTOM' })
      .expect(400);
  });

  it('[IAM-ADMIN-DS-004] DELETE 内置 DataScope 被拒', async () => {
    const builtIn = await prisma.dataScope.findFirst({ where: { isBuiltIn: true } });
    if (!builtIn) throw new Error('seed 缺少内置 DataScope');

    await request(app.getHttpServer())
      .delete(`/api/v1/iam/data-scopes/${builtIn.id}`)
      .set('Authorization', `Bearer ${adminToken}`)
      .expect(400);
  });

  it('[IAM-ADMIN-DS-005] PATCH 更新 name 成功，落 UPDATE 审计', async () => {
    const created = await request(app.getHttpServer())
      .post('/api/v1/iam/data-scopes')
      .set('Authorization', `Bearer ${adminToken}`)
      .send({ code: `UPD_${Date.now()}`, name: '原名', scopeType: 'SELF' })
      .expect(201);

    await request(app.getHttpServer())
      .patch(`/api/v1/iam/data-scopes/${created.body.data.id}`)
      .set('Authorization', `Bearer ${adminToken}`)
      .send({ name: '改后' })
      .expect(200);

    const after = await prisma.dataScope.findUnique({ where: { id: created.body.data.id } });
    expect(after?.name).toBe('改后');
  });
});
