import cron from "node-cron";
import { processBeloQuote } from "./belo.service";
import { processBlueQuote } from "./blue.service";
import { processBnaQuote } from "./bna.service";
import { logger } from "../../lib/logger";
import { eventBus } from "../../lib/event-bus";

async function safeProcess(
  name: string,
  fn: () => Promise<void>,
): Promise<void> {
  try {
    await fn();
    logger.info(`${name} quote processed successfully`);
  } catch (error) {
    logger.error(error, `Error processing ${name} quote`);
  }
}

const QUOTES = [
  { name: "BELO", fn: processBeloQuote },
  { name: "BLUE", fn: processBlueQuote },
  { name: "BNA", fn: processBnaQuote },
] as const;

export function startQuoteJob(): void {
  cron.schedule("*/10 * * * *", async () => {
    logger.info("Fetching quotes...");
    await Promise.all(QUOTES.map((q) => safeProcess(q.name, q.fn)));
    eventBus.emit("quotes-updated");
  });

  logger.info("Cron scheduled: every 10 minutes");
}
