import { Test, type TestingModule } from '@nestjs/testing';
import { HealthService } from '../health.service';
import { PrismaService } from '../../../../infrastructure/database/prisma/prisma.service';
import { RedisService } from '../../../../infrastructure/redis/redis.service';
import { HealthCheckStatus, ServiceStatus } from '../../../../common/enums';

describe('HealthService', () => {
  let prismaMock: { $queryRaw: jest.Mock };
  let redisMock: { getClient: jest.Mock };

  const buildService = async (): Promise<HealthService> => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        HealthService,
        { provide: PrismaService, useValue: prismaMock },
        { provide: RedisService, useValue: redisMock },
      ],
    }).compile();
    return module.get<HealthService>(HealthService);
  };

  beforeEach(() => {
    prismaMock = { $queryRaw: jest.fn().mockResolvedValue([{ '?column?': 1 }]) };
    redisMock = {
      getClient: jest.fn().mockReturnValue({
        ping: jest.fn().mockResolvedValue('PONG'),
      }),
    };
  });

  it('returns OK when both up', async () => {
    const service = await buildService();
    expect((await service.check()).status).toBe(HealthCheckStatus.OK);
  });

  it('returns DOWN when both down', async () => {
    prismaMock.$queryRaw = jest.fn().mockRejectedValue(new Error('db'));
    redisMock.getClient = jest.fn().mockReturnValue({
      ping: jest.fn().mockRejectedValue(new Error('redis')),
    });
    const service = await buildService();
    expect((await service.check()).status).toBe(HealthCheckStatus.DOWN);
  });

  it('returns DEGRADED when only redis down', async () => {
    redisMock.getClient = jest.fn().mockReturnValue({
      ping: jest.fn().mockResolvedValue('not-pong'),
    });
    const service = await buildService();
    const result = await service.check();
    expect(result.status).toBe(HealthCheckStatus.DEGRADED);
    expect(result.services.database).toBe(ServiceStatus.UP);
  });

  it('returns DEGRADED when only db down', async () => {
    prismaMock.$queryRaw = jest.fn().mockRejectedValue(new Error('db'));
    const service = await buildService();
    const result = await service.check();
    expect(result.status).toBe(HealthCheckStatus.DEGRADED);
    expect(result.services.redis).toBe(ServiceStatus.UP);
  });

  it('emits ISO timestamp', async () => {
    const service = await buildService();
    const result = await service.check();
    expect(new Date(result.timestamp).toISOString()).toBe(result.timestamp);
  });
});
