import { LessThan } from 'typeorm';
import { NotificationRetentionScheduler } from './notification-retention.scheduler';

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

  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 NotificationRetentionScheduler(repository as any, configService as any, logger as any);
  });

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

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

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

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

    await scheduler.cleanupOldNotifications();

    expect(logger.info).toHaveBeenCalledWith({
      event: 'notification_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.cleanupOldNotifications()).resolves.toBeUndefined();

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