/**
 * FFAI Agent — admin/rules CRUD API 集成测试
 *
 * 覆盖：
 *   - POST 缺 name / primary 返 400
 *   - POST + GET + PATCH + DELETE happy path
 *   - 跨 org PATCH/DELETE 必拒（404，避免泄漏存在性）
 *   - 无 JWT 返 401
 */
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('FFAI Agent - Admin Rules CRUD API', () => {
  let app: INestApplication;
  let prisma: PrismaService;
  let adminToken: string;
  let orgId: string;

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

  beforeEach(async () => {
    const ctx = await setupIntegrationTest(app, prisma);
    adminToken = ctx.adminToken;
    const org = await prisma.organization.findFirst({ orderBy: { createdAt: 'asc' } });
    orgId = org!.id;
  });

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

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

  it('[AGENT-ADMR-001] POST /agent/admin/rules 缺 name 返 400', async () => {
    await request(app.getHttpServer())
      .post('/api/v1/agent/admin/rules')
      .set('Authorization', `Bearer ${adminToken}`)
      .set('X-Organization-Id', orgId)
      .send({ primary: { provider: 'qwen', model: 'qwen-plus' }, pattern: {} })
      .expect(400);
  });

  it('[AGENT-ADMR-002] POST /agent/admin/rules 缺 primary 返 400', async () => {
    await request(app.getHttpServer())
      .post('/api/v1/agent/admin/rules')
      .set('Authorization', `Bearer ${adminToken}`)
      .set('X-Organization-Id', orgId)
      .send({ name: 't_admr_002', pattern: {} })
      .expect(400);
  });

  it('[AGENT-ADMR-003] POST + GET + PATCH + DELETE happy path', async () => {
    // POST
    const created = await request(app.getHttpServer())
      .post('/api/v1/agent/admin/rules')
      .set('Authorization', `Bearer ${adminToken}`)
      .set('X-Organization-Id', orgId)
      .send({
        name: 't_admr_003',
        priority: 100,
        pattern: { taskType: 'translation' },
        primary: { provider: 'qwen', model: 'qwen-turbo' },
      })
      .expect(201);
    expect(created.body.data.name).toBe('t_admr_003');
    const ruleId = created.body.data.id;

    // GET
    const listed = await request(app.getHttpServer())
      .get('/api/v1/agent/admin/rules')
      .set('Authorization', `Bearer ${adminToken}`)
      .set('X-Organization-Id', orgId)
      .expect(200);
    expect(listed.body.data.items.some((r: { id: string }) => r.id === ruleId)).toBe(true);

    // PATCH
    const patched = await request(app.getHttpServer())
      .patch(`/api/v1/agent/admin/rules/${ruleId}`)
      .set('Authorization', `Bearer ${adminToken}`)
      .set('X-Organization-Id', orgId)
      .send({ priority: 50, enabled: false })
      .expect(200);
    expect(patched.body.data.priority).toBe(50);
    expect(patched.body.data.enabled).toBe(false);

    // DELETE
    const deleted = await request(app.getHttpServer())
      .delete(`/api/v1/agent/admin/rules/${ruleId}`)
      .set('Authorization', `Bearer ${adminToken}`)
      .set('X-Organization-Id', orgId)
      .expect(200);
    expect(deleted.body.data.deleted).toBe(true);

    // 已删除后再 PATCH 应 404
    await request(app.getHttpServer())
      .patch(`/api/v1/agent/admin/rules/${ruleId}`)
      .set('Authorization', `Bearer ${adminToken}`)
      .set('X-Organization-Id', orgId)
      .send({ enabled: true })
      .expect(404);
  });

  it('[AGENT-ADMR-004] 跨 org PATCH/DELETE 必拒 404（不泄漏存在性）', async () => {
    const otherOrg = await prisma.organization.create({
      data: { code: `T_admr_${Date.now()}`, name: 'other-org-admr' },
    });
    const otherRule = await prisma.modelRoutingRule.create({
      data: {
        organizationId: otherOrg.id,
        scope: 'ORGANIZATION',
        scopeRefId: otherOrg.id,
        name: 't_admr_004_other',
        priority: 500,
        pattern: {} as never,
        primary: { provider: 'qwen', model: 'qwen-plus' } as never,
        fallbacks: [] as never,
        createdById: '00000000-0000-0000-0000-000000000000',
      },
    });

    await request(app.getHttpServer())
      .patch(`/api/v1/agent/admin/rules/${otherRule.id}`)
      .set('Authorization', `Bearer ${adminToken}`)
      .set('X-Organization-Id', orgId)
      .send({ enabled: false })
      .expect(404);

    await request(app.getHttpServer())
      .delete(`/api/v1/agent/admin/rules/${otherRule.id}`)
      .set('Authorization', `Bearer ${adminToken}`)
      .set('X-Organization-Id', orgId)
      .expect(404);
  });

  it('[AGENT-ADMR-005] 无 JWT 返 401', async () => {
    await request(app.getHttpServer())
      .get('/api/v1/agent/admin/rules')
      .set('X-Organization-Id', orgId)
      .expect(401);
  });
});
