/**
 * @copyright nhcarrigan
 * @license Naomi's Public License
 * @author Naomi Carrigan
 */
import { ChannelType, type Client } from "discord.js";
import { logHandler } from "../utils/logHandler.js";
import type { WeatherCache } from "../interfaces/weatherCache.js";

/**
 * Module to fetch the configured channels for sending weather forecasts.
 * @param bot - The bot's Discord instance.
 * @returns The configured channels for sending weather forecasts.
 */
export const loadChannels = async(
  bot: Client,
): Promise<WeatherCache["channels"]> => {
  try {
    const guildId = process.env.HOME_GUILD_ID ?? "";
    const rudaniaId = process.env.RUDANIA_ID ?? "";
    const inarikoId = process.env.INARIKO_ID ?? "";
    const vhintlId = process.env.VHINTL_ID ?? "";

    const guild = await bot.guilds.fetch(guildId);
    const Rudania = await guild.channels.fetch(rudaniaId);
    const Inariko = await guild.channels.fetch(inarikoId);
    const Vhintl = await guild.channels.fetch(vhintlId);

    if (
      !Rudania
      || !Inariko
      || !Vhintl
      || !("send" in Rudania && "send" in Inariko && "send" in Vhintl)
      || Rudania.type !== ChannelType.GuildText
      || Inariko.type !== ChannelType.GuildText
      || Vhintl.type !== ChannelType.GuildText
    ) {
      logHandler.log("error", "Cannot locate the forecast channels!");
      process.exit(1);
    }

    return { Inariko, Rudania, Vhintl };
  } catch (error) {
    logHandler.log("error", error);
    process.exit(1);
  }
};
