import { describe, it, expect } from 'vitest';
import type { Querier } from '@platform-modules/db';
import { runHealthChecks } from './health.js';

// Minimal fake Querier — db/health's probe only calls `.execute(sql`SELECT 1`)`.
function fakeDb(execute: () => Promise<unknown>): Querier {
  return { execute } as unknown as Querier;
}

describe('runHealthChecks', () => {
  it('db reachable → overall ok, single db check ok with latency', async () => {
    const result = await runHealthChecks(fakeDb(async () => []));
    expect(result.status).toBe('ok');
    expect(result.checks).toHaveLength(1);
    expect(result.checks[0]).toMatchObject({ name: 'db', status: 'ok' });
    expect(typeof result.checks[0]!.latencyMs).toBe('number');
  });

  it('db query throws → overall down, db check down, NEVER throws (availability floor)', async () => {
    const result = await runHealthChecks(
      fakeDb(async () => {
        // A driver error carrying a DSN/creds — must NOT surface in the result detail.
        throw new Error('connection refused: postgres://user:pw@host/db');
      }),
    );
    expect(result.status).toBe('down');
    expect(result.checks[0]).toMatchObject({ name: 'db', status: 'down' });
    // info-disclosure floor: db/health returns a GENERIC detail, never the raw driver error.
    expect(result.checks[0]!.detail ?? '').not.toContain('postgres://');
    expect(result.checks[0]!.detail ?? '').not.toContain('pw');
  });
});
