import { LessThan } from 'typeorm';
import { LogRetentionScheduler } from './log-retention.scheduler';

describe('LogRetentionScheduler', () => {
  const repository = { delete: jest.fn() };
  const configService = { get: jest.fn() };
  const logger = { info: jest.fn(), error: jest.fn() };
  let scheduler: LogRetentionScheduler;

  beforeEach(() => {
    jest.clearAllMocks();
    jest.useFakeTimers().setSystemTime(new Date('2026-08-04T12:00:00.000Z'));
    configService.get.mockReturnValue(365);
    repository.delete.mockResolvedValue({ affected: 3 });
    scheduler = new LogRetentionScheduler(repository as any, configService as any, logger as any);
  });

  afterEach(() => {
    jest.useRealTimers();
  });

  it('deletes log entries older than the configured retention window', async () => {
    await scheduler.cleanupOldLogs();

    expect(configService.get).toHaveBeenCalledWith('app.logRetentionDays');
    expect(repository.delete).toHaveBeenCalledWith({
      createdAt: LessThan(new Date('2025-08-04T12:00:00.000Z')),
    });
  });

  it('uses whatever retention window the config reports', async () => {
    configService.get.mockReturnValue(30);

    await scheduler.cleanupOldLogs();

    expect(repository.delete).toHaveBeenCalledWith({
      createdAt: LessThan(new Date('2026-07-05T12:00:00.000Z')),
    });
  });

  it('logs the number of deleted entries', async () => {
    repository.delete.mockResolvedValue({ affected: 7 });

    await scheduler.cleanupOldLogs();

    expect(logger.info).toHaveBeenCalledWith({
      event: 'log_retention_cleanup_run',
      details: 'deletedCount=7 retentionDays=365',
      userId: -1,
    });
  });

  it('logs and does not rethrow when the delete fails', async () => {
    repository.delete.mockRejectedValue(new Error('connection reset'));

    await expect(scheduler.cleanupOldLogs()).resolves.toBeUndefined();

    expect(logger.error).toHaveBeenCalledWith({
      event: 'log_retention_cleanup_run_fail',
      details: 'connection reset',
      userId: -1,
    });
    expect(logger.info).not.toHaveBeenCalled();
  });
});
