import { ConfigService } from '@nestjs/config';
import { AppLoggerService } from '../logging/app-logger.service';
import { ShutdownCoordinatorService } from './shutdown-coordinator.service';

describe('ShutdownCoordinatorService', () => {
  const createService = () => {
    const config = { get: jest.fn().mockReturnValue(25) } as unknown as ConfigService;
    const logger = { warn: jest.fn(), log: jest.fn() } as unknown as AppLoggerService;
    return { logger, service: new ShutdownCoordinatorService(config, logger) };
  };

  it('tracks active requests without allowing the counter below zero', () => {
    const { service } = createService();
    expect(service.beginRequest()).toBe(true);
    expect(service.getActiveRequests()).toBe(1);
    service.endRequest();
    service.endRequest();
    expect(service.getActiveRequests()).toBe(0);
  });

  it('enters drain mode before shutdown and refuses new requests', async () => {
    const { logger, service } = createService();
    await service.beforeApplicationShutdown('SIGTERM');

    expect(service.getState()).toBe('draining');
    expect(service.beginRequest()).toBe(false);
    expect(logger.warn).toHaveBeenCalledWith(
      expect.stringContaining('SIGTERM'),
      'ShutdownCoordinator',
    );

    service.onApplicationShutdown('SIGTERM');
    expect(service.getState()).toBe('stopped');
  });
});
