/**
 * FFAI Agent — routing decisions API 集成测试
 *
 * 覆盖：
 *   - GET /agent/routing/decisions system:admin 可查本 org 决策
 *   - 跨 org 决策不返回（org 隔离）
 *   - 无 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 - Routing API', () => {
  let app: INestApplication;
  let prisma: PrismaService;
  let adminToken: string;
  let adminUserId: 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;
    adminUserId = ctx.adminUser.id;
    const org = await prisma.organization.findFirst({ orderBy: { createdAt: 'asc' } });
    orgId = org!.id;
  });

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

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

  it('[AGENT-ROU-001] GET /agent/routing/decisions admin 可查本 org 决策', async () => {
    const sess = await prisma.agentSession.create({
      data: { organizationId: orgId, createdById: adminUserId, title: 't_routing_001' },
    });
    await prisma.modelRoutingDecision.create({
      data: {
        organizationId: orgId,
        sessionId: sess.id,
        request: { prompt: 't_routing_001', surface: 'web' } as never,
        decision: { primary: { model: 'qwen-plus' }, matchSource: 'rule' } as never,
        matchSource: 'RULE',
        primaryProvider: 'qwen',
        primaryModel: 'qwen-plus',
      },
    });

    const res = await request(app.getHttpServer())
      .get('/api/v1/agent/routing/decisions')
      .set('Authorization', `Bearer ${adminToken}`)
      .set('X-Organization-Id', orgId)
      .expect(200);

    expect(Array.isArray(res.body.data.items)).toBe(true);
    expect(res.body.data.items.some((d: { sessionId: string }) => d.sessionId === sess.id)).toBe(true);
  });

  it('[AGENT-ROU-002] GET /agent/routing/decisions 跨 org 决策不在返回中', async () => {
    const otherOrg = await prisma.organization.create({
      data: { code: `T_routing_${Date.now()}`, name: 'other-org-routing' },
    });
    const otherSess = await prisma.agentSession.create({
      data: {
        organizationId: otherOrg.id,
        createdById: '00000000-0000-0000-0000-000000000000',
        title: 't_routing_002_other',
      },
    });
    await prisma.modelRoutingDecision.create({
      data: {
        organizationId: otherOrg.id,
        sessionId: otherSess.id,
        request: { prompt: 't_routing_002', surface: 'web' } as never,
        decision: { primary: { model: 'qwen-max' }, matchSource: 'rule' } as never,
        matchSource: 'RULE',
        primaryProvider: 'qwen',
        primaryModel: 'qwen-max',
      },
    });

    const res = await request(app.getHttpServer())
      .get('/api/v1/agent/routing/decisions')
      .set('Authorization', `Bearer ${adminToken}`)
      .set('X-Organization-Id', orgId)
      .expect(200);

    expect(res.body.data.items.every((d: { organizationId: string }) => d.organizationId === orgId)).toBe(true);
  });

  it('[AGENT-ROU-003] GET /agent/routing/decisions 无 JWT 返 401', async () => {
    await request(app.getHttpServer())
      .get('/api/v1/agent/routing/decisions')
      .set('X-Organization-Id', orgId)
      .expect(401);
  });
});
