import { ConsistencyService } from './consistency.service';

describe('ConsistencyService', () => {
  const makePrisma = () => {
    const counts = {
      product: 1,
      project: 2,
      version: 3,
      requirement: 4,
      versionPlan: 5,
      devTask: 6,
      testCase: 7,
      bug: 8,
      user: 9,
      taskCategory: 10,
      taskWorklog: 11,
      overtimeRecord: 12,
      workActivity: 13,
      auditEvent: 14,
    };
    const prisma: any = {
      $queryRawUnsafe: jest.fn((sql: string) => {
        if (sql.includes('dev_tasks') && sql.includes("version_id = ''")) return Promise.resolve([{ count: 1n }]);
        if (sql.includes('requirements') && sql.includes('missing_version')) return Promise.resolve([{ count: 2n }]);
        if (sql.includes('audit_events') && sql.includes("entity_type = 'bug'")) return Promise.resolve([{ count: 0n }]);
        return Promise.resolve([{ count: 0n }]);
      }),
    };
    for (const [model, count] of Object.entries(counts)) {
      prisma[model] = { count: jest.fn().mockResolvedValue(count) };
    }
    return prisma;
  };

  it('returns counts plus error/warn consistency groups', async () => {
    const prisma = makePrisma();
    const service = new ConsistencyService(prisma);

    const result = await service.run();

    expect(result.status).toBe('fail');
    expect(result.counts.devTasks).toBe(6);
    expect(result.summary.errors).toBeGreaterThan(0);
    expect(result.summary.warnings).toBeGreaterThan(0);
    expect(result.checks.partitionKeys).toEqual(
      expect.arrayContaining([
        expect.objectContaining({
          id: 'dev_tasks.version_id.present',
          severity: 'error',
          count: 1,
        }),
      ]),
    );
    expect(result.checks.orphanReferences).toEqual(
      expect.arrayContaining([
        expect.objectContaining({
          id: 'requirements.version_id.exists',
          severity: 'error',
          count: 2,
        }),
      ]),
    );
    expect(result.checks.auditCoverage).toEqual(
      expect.arrayContaining([
        expect.objectContaining({
          id: 'audit.coverage.bug',
          severity: 'warn',
          count: 0,
        }),
      ]),
    );
  });
});
