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

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

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

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

export const medicationReminderQueueName = 'medication-reminders';

export const medicationReminderQueue = new Queue<MedicationReminderJobData, MedicationReminderJobResult>(medicationReminderQueueName, {
  connection: redisConnection,
  defaultJobOptions: {
    attempts: 3,
    backoff: {
      type: 'exponential',
      delay: 60_000,
    },
    removeOnComplete: 100,
    removeOnFail: 1_000,
  },
});

export const enqueueMedicationReminderJob = (
  runDate: string,
  currentTime: string,
): Promise<Job<MedicationReminderJobData, MedicationReminderJobResult>> =>
  medicationReminderQueue.add(
    'run-medication-reminders',
    {
      runDate,
      currentTime,
      requestedBy: 'scheduler',
    },
    {
      jobId: `medication-reminders-${runDate}-${currentTime.slice(0, 2)}`,
    },
  );

export const closeMedicationReminderQueue = async () => {
  await medicationReminderQueue.close();
};

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