/**
 * @copyright nhcarrigan
 * @license Naomi's Public License
 * @author Naomi Carrigan
 */
import { scheduleJob } from "node-schedule";
import { errorHandler } from "../utils/errorHandler.js";
import { logHandler } from "../utils/logHandler.js";
import { generateWeatherEmbed } from "./generateWeatherEmbed.js";
import { getWeatherForecast } from "./getWeatherForecast.js";
import type { WeatherCache } from "../interfaces/weatherCache.js";

/**
 * Schedules a CRON job for sending weather forecasts to the appropriate channels.
 * @param cache - The weather cache.
 */
export const scheduleForecasts = (cache: WeatherCache): void => {
  logHandler.log("info", "Scheduling weather forecasts...");
  // Run daily at 5AM PST to get 8AM EST.
  // eslint-disable-next-line @typescript-eslint/no-misused-promises
  scheduleJob("0 0 5 * * *", async() => {
    try {
      cache.Rudania = getWeatherForecast("Rudania");
      cache.Inariko = getWeatherForecast("Inariko");
      cache.Vhintl = getWeatherForecast("Vhintl");

      const rudania = await generateWeatherEmbed(cache.Rudania);
      await cache.channels.Rudania.send(rudania);
      const inariko = await generateWeatherEmbed(cache.Inariko);
      await cache.channels.Inariko.send(inariko);
      const vhintl = await generateWeatherEmbed(cache.Vhintl);
      await cache.channels.Vhintl.send(vhintl);
    } catch (error) {
      const errorId = await errorHandler(error, "scheduled forecast");
      await cache.channels.Rudania.send(errorId);
    }
  });
};
