import { describe, expect, it } from '@jest/globals';
import express from 'express';
import request from 'supertest';
import healthRouter from '../../../routes/health';
import { mockRedisClient, prismaMock } from '../../setup';

describe('readiness Redis cleanup', () => {
  it('disconnects the request-scoped client after a successful ping', async () => {
    prismaMock.$queryRaw.mockResolvedValue([{ result: 1 }]);
    mockRedisClient.ping.mockResolvedValue('PONG');

    const app = express();
    app.use('/health', healthRouter);

    await request(app).get('/health/ready').expect(200);

    expect(mockRedisClient.disconnect).toHaveBeenCalledTimes(1);
  });

  it('always disconnects the request-scoped client when ping fails', async () => {
    prismaMock.$queryRaw.mockResolvedValue([{ result: 1 }]);
    mockRedisClient.ping.mockRejectedValue(new Error('Redis unavailable'));

    const app = express();
    app.use('/health', healthRouter);

    await request(app).get('/health/ready').expect(503);

    expect(mockRedisClient.disconnect).toHaveBeenCalledTimes(1);
  });
});
