/**
 * Audit 查询端点集成测试
 *
 * 覆盖：logs / logs/:id / logs/:id/verify / entity / user / financial / sensitive / trace / statistics
 * 含 C1/C2 契约字段断言（已在 commit 47638538 修复）
 */

import { INestApplication } from '@nestjs/common';
import request from 'supertest';
import { PrismaService } from '@/core/database/prisma/prisma.service';
import { createTestApp } from '../../helpers/app.helper';
import { setupIntegrationTest } from '../../helpers/test-setup.helper';
import { cleanupDatabase } from '../../helpers/cleanup.helper';

describe('Audit Query Endpoints', () => {
  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('[AUDIT-Q-001] GET /audit/logs 返回分页结构', async () => {
    const res = await request(app.getHttpServer())
      .get('/api/v1/audit/logs?limit=5')
      .set('Authorization', `Bearer ${adminToken}`)
      .expect(200);
    const d = res.body.data;
    expect(Array.isArray(d.items)).toBe(true);
    expect(typeof d.total).toBe('number');
    expect(d.page).toBe(1);
    expect(d.limit).toBe(5);
  });

  it('[AUDIT-Q-002] GET /audit/logs items 含 C1 修复字段（userId/ipAddress/userAgent）', async () => {
    const res = await request(app.getHttpServer())
      .get('/api/v1/audit/logs?limit=1')
      .set('Authorization', `Bearer ${adminToken}`)
      .expect(200);
    if (res.body.data.items.length === 0) return;
    const item = res.body.data.items[0];
    expect(item).toHaveProperty('userId');
    expect(item).toHaveProperty('ipAddress');
    expect(item).toHaveProperty('userAgent');
  });

  it('[AUDIT-Q-003] GET /audit/logs/:id 返回详情含 C2 字段', async () => {
    const list = await request(app.getHttpServer())
      .get('/api/v1/audit/logs?limit=1')
      .set('Authorization', `Bearer ${adminToken}`)
      .expect(200);
    if (list.body.data.items.length === 0) return;
    const id = list.body.data.items[0].id;

    const res = await request(app.getHttpServer())
      .get(`/api/v1/audit/logs/${id}`)
      .set('Authorization', `Bearer ${adminToken}`)
      .expect(200);
    const d = res.body.data;
    expect(d.id).toBe(id);
    expect(d).toHaveProperty('businessType');
    expect(d).toHaveProperty('businessKey');
    expect(d).toHaveProperty('signature');
    expect(d).toHaveProperty('archivedAt');
    expect(d).toHaveProperty('previousHash');
    expect(d).toHaveProperty('currentHash');
  });

  it('[AUDIT-Q-004] GET /audit/logs/:id/verify 返回校验结果', async () => {
    const list = await request(app.getHttpServer())
      .get('/api/v1/audit/logs?limit=1')
      .set('Authorization', `Bearer ${adminToken}`)
      .expect(200);
    if (list.body.data.items.length === 0) return;
    const id = list.body.data.items[0].id;

    const res = await request(app.getHttpServer())
      .get(`/api/v1/audit/logs/${id}/verify`)
      .set('Authorization', `Bearer ${adminToken}`)
      .expect(200);
    expect(res.body.data).toHaveProperty('valid');
    expect(res.body.data).toHaveProperty('storedHash');
    expect(res.body.data).toHaveProperty('calculatedHash');
  });

  it('[AUDIT-Q-005] GET /audit/financial 跨度 > 365 天 → 400', async () => {
    await request(app.getHttpServer())
      .get('/api/v1/audit/financial?startDate=2024-01-01&endDate=2026-12-31')
      .set('Authorization', `Bearer ${adminToken}`)
      .expect(400);
  });

  it('[AUDIT-Q-006] GET /audit/financial 合法跨度 → 200', async () => {
    const res = await request(app.getHttpServer())
      .get('/api/v1/audit/financial?startDate=2026-01-01&endDate=2026-12-31&limit=2')
      .set('Authorization', `Bearer ${adminToken}`)
      .expect(200);
    expect(Array.isArray(res.body.data.items)).toBe(true);
  });

  it('[AUDIT-Q-007] GET /audit/sensitive 返回分页 + summary', async () => {
    const res = await request(app.getHttpServer())
      .get('/api/v1/audit/sensitive?limit=2')
      .set('Authorization', `Bearer ${adminToken}`)
      .expect(200);
    expect(res.body.data).toHaveProperty('items');
    expect(res.body.data).toHaveProperty('total');
  });

  it('[AUDIT-Q-008] POST /audit/statistics 返回汇总结构', async () => {
    const res = await request(app.getHttpServer())
      .post('/api/v1/audit/statistics')
      .set('Authorization', `Bearer ${adminToken}`)
      .send({ startDate: '2025-01-01', endDate: '2026-12-31' })
      .expect(201);
    const d = res.body.data;
    expect(d.summary).toBeDefined();
    expect(d.summary.total).toBeGreaterThanOrEqual(0);
    expect(Array.isArray(d.byModule)).toBe(true);
    expect(Array.isArray(d.byAction)).toBe(true);
    expect(Array.isArray(d.byDay)).toBe(true);
  });

  it('[AUDIT-Q-009] GET /audit/user/:userId 不存在用户返回空 history', async () => {
    const res = await request(app.getHttpServer())
      .get('/api/v1/audit/user/00000000-0000-0000-0000-000000000000')
      .set('Authorization', `Bearer ${adminToken}`)
      .expect(200);
    expect(res.body.data).toHaveProperty('operations');
    expect(Array.isArray(res.body.data.operations)).toBe(true);
  });
});