/**
 * @copyright nhcarrigan
 * @license Naomi's Public License
 * @author Naomi Carrigan
 */
import { REST, Routes, type Client, WebhookClient } from "discord.js";
import { commandList } from "../../commands/_commandList.js";
import { scheduleForecasts } from "../../modules/scheduleForecasts.js";
import { logHandler } from "../../utils/logHandler.js";
import type { WeatherCache } from "../../interfaces/weatherCache.js";

/**
 * Handler for the READY event from Discord. Logs that the bot is connected,
 * then registers the guild slash commands.
 * @param bot - The bot's Discord instance.
 * @param cache - The cache of weather data.
 */
export const onReady = async (
  bot: Client,
  cache: WeatherCache
): Promise<void> => {
  const webhook = new WebhookClient({ url: process.env.DEBUG_HOOK as string });

  await webhook.send("Ruu Bot is online!");
  logHandler.log("info", "Connected to Discord!");

  const rest = new REST({ version: "9" }).setToken(
    process.env.DISCORD_TOKEN ?? ""
  );

  const commandData = commandList.map((command) => {
    return command.data.toJSON();
  });

  await rest.put(
    Routes.applicationGuildCommands(
      bot.user?.id ?? "oopsie whoopsie",
      process.env.HOME_GUILD_ID ?? ""
    ),
    { body: commandData }
  );

  logHandler.log("info", "Registered commands!");

  scheduleForecasts(cache);
};
