import { Queue, type Job } from 'bullmq';

import { redisConnection } from './redisConnection.js';

export type BirdMilestoneReminderJobData = {
  runDate: string;
  requestedBy: 'scheduler';
};

export type BirdMilestoneReminderJobResult = {
  runDate: string;
  checked: number;
  sent: number;
  skipped: number;
  failed: number;
};

export const birdMilestoneReminderQueueName = 'bird-milestone-reminders';

export const birdMilestoneReminderQueue = new Queue<BirdMilestoneReminderJobData, BirdMilestoneReminderJobResult>(
  birdMilestoneReminderQueueName,
  {
    connection: redisConnection,
    defaultJobOptions: {
      attempts: 3,
      backoff: {
        type: 'exponential',
        delay: 60_000,
      },
      removeOnComplete: 100,
      removeOnFail: 1_000,
    },
  },
);

export const enqueueBirdMilestoneReminderJob = (runDate: string): Promise<Job<BirdMilestoneReminderJobData, BirdMilestoneReminderJobResult>> =>
  birdMilestoneReminderQueue.add(
    'run-daily-reminders',
    {
      runDate,
      requestedBy: 'scheduler',
    },
    {
      jobId: `bird-milestone-reminders-${runDate}`,
    },
  );

export const closeBirdMilestoneReminderQueue = async () => {
  await birdMilestoneReminderQueue.close();
};

export const getBirdMilestoneReminderQueueCounts = () =>
  birdMilestoneReminderQueue.getJobCounts('waiting', 'active', 'delayed', 'completed', 'failed');
