import { HealthCheckError } from '@nestjs/terminus';
import { PrismaHealthIndicator } from '../prisma.health';

describe('PrismaHealthIndicator', () => {
  let indicator: PrismaHealthIndicator;
  let mockPrisma: { $queryRawUnsafe: ReturnType<typeof vi.fn> };

  beforeEach(() => {
    mockPrisma = { $queryRawUnsafe: vi.fn() };
    indicator = new PrismaHealthIndicator(mockPrisma as any);
  });

  it('returns healthy status when database responds to SELECT 1', async () => {
    mockPrisma.$queryRawUnsafe.mockResolvedValue([{ '?column?': 1 }]);

    const result = await indicator.isHealthy('database');

    expect(mockPrisma.$queryRawUnsafe).toHaveBeenCalledWith('SELECT 1');
    expect(result).toEqual({ database: { status: 'up' } });
  });

  it('throws HealthCheckError when database query fails', async () => {
    mockPrisma.$queryRawUnsafe.mockRejectedValue(new Error('Connection refused'));

    await expect(indicator.isHealthy('database')).rejects.toThrow(HealthCheckError);
  });

  it('includes the key name in the error status', async () => {
    mockPrisma.$queryRawUnsafe.mockRejectedValue(new Error('timeout'));

    try {
      await indicator.isHealthy('db');
      expect.unreachable('Should have thrown');
    } catch (error) {
      expect(error).toBeInstanceOf(HealthCheckError);
      expect((error as HealthCheckError).causes).toEqual({ db: { status: 'down' } });
    }
  });
});
