import { ServiceUnavailableException } from '@nestjs/common';
import { HealthController } from './health.controller';

describe('HealthController', () => {
  function createController(options?: { database?: boolean; redis?: boolean }) {
    const database = options?.database ?? true;
    const redis = options?.redis ?? true;
    const prisma = {
      $queryRaw: jest.fn().mockImplementation(() => {
        if (!database) throw new Error('database unavailable');
        return Promise.resolve([{ ok: 1 }]);
      }),
    };
    const redisService = {
      raw: {
        ping: jest.fn().mockImplementation(() => {
          if (!redis) throw new Error('redis unavailable');
          return Promise.resolve('PONG');
        }),
      },
    };

    return new HealthController(prisma as never, redisService as never);
  }

  it('reports liveness without external checks', () => {
    expect(createController().live()).toEqual({ status: 'ok' });
  });

  it('reports readiness when database and redis respond', async () => {
    await expect(createController().ready()).resolves.toEqual({
      status: 'ok',
      checks: { database: 'ok', redis: 'ok' },
    });
  });

  it('fails readiness when a dependency is unavailable', async () => {
    await expect(createController({ redis: false }).ready()).rejects.toBeInstanceOf(
      ServiceUnavailableException,
    );
  });
});
