import { Worker } from 'bullmq';

import { ensureSchema } from './db/schema.js';
import { db } from './db/client.js';
import { runBirdMilestoneReminders, startBirdMilestoneReminderScheduler } from './app.js';
import {
  birdMilestoneReminderQueueName,
  closeBirdMilestoneReminderQueue,
  type BirdMilestoneReminderJobData,
  type BirdMilestoneReminderJobResult,
} from './queues/birdMilestoneReminderQueue.js';
import { redisConnection } from './queues/redisConnection.js';

let birdMilestoneWorker: Worker<BirdMilestoneReminderJobData, BirdMilestoneReminderJobResult> | null = null;

const startWorker = async () => {
  await ensureSchema();

  birdMilestoneWorker = new Worker<BirdMilestoneReminderJobData, BirdMilestoneReminderJobResult>(
    birdMilestoneReminderQueueName,
    async (job) => {
      const result = await runBirdMilestoneReminders(job.data.runDate);
      console.log(
        `Bird milestone reminder job completed for ${result.runDate}: checked=${result.checked}, sent=${result.sent}, skipped=${result.skipped}, failed=${result.failed}`,
      );
      return result;
    },
    {
      connection: redisConnection,
      concurrency: 1,
    },
  );

  birdMilestoneWorker.on('failed', (job, error) => {
    console.error(`Bird milestone reminder job failed: id=${job?.id ?? 'unknown'}`, error);
  });

  startBirdMilestoneReminderScheduler();
  console.log('FlockPal worker started.');
};

const shutdown = async (signal: string) => {
  console.log(`FlockPal worker received ${signal}; shutting down.`);
  await birdMilestoneWorker?.close();
  await closeBirdMilestoneReminderQueue();
  await db.close();
  process.exit(0);
};

process.on('SIGINT', () => {
  void shutdown('SIGINT');
});

process.on('SIGTERM', () => {
  void shutdown('SIGTERM');
});

startWorker().catch((error) => {
  console.error('Failed to start FlockPal worker', error);
  process.exit(1);
});
