/**
 * @copyright nhcarrigan
 * @license Naomi's Public License
 * @author Naomi Carrigan
 */
import { SlashCommandBuilder } from "discord.js";
import { forecastChoices } from "../config/forecastChoices.js";
import { generateWeatherEmbed } from "../modules/generateWeatherEmbed.js";
import { getWeatherForecast } from "../modules/getWeatherForecast.js";
import { errorHandler } from "../utils/errorHandler.js";
import type { Command } from "../interfaces/commands/command.js";
import type { RegionName } from "../interfaces/weather/names/regionName.js";

const isRegionName = (region: string): region is RegionName => {
  return [ "Rudania", "Inariko", "Vhintl" ].includes(region);
};

export const forecast: Command = {
  data: new SlashCommandBuilder().
    setName("forecast").
    setDescription("Get the weather forecast for a specific region.").
    addStringOption((option) => {
      return option.
        setName("region").
        setDescription("The region to get a forecast for.").
        setRequired(true).
        addChoices(forecastChoices);
    }),
  run: async(interaction, cache) => {
    try {
      await interaction.deferReply();
      const region = interaction.options.getString("region", true);
      if (!isRegionName(region)) {
        await interaction.editReply({ content: `Invalid region: ${region}` });
        return;
      }
      const forecastResult = cache[region] ?? getWeatherForecast(region);
      const response = await generateWeatherEmbed(forecastResult);
      await interaction.editReply(response);
    } catch (error) {
      const response = await errorHandler(error, "forecast command");
      await interaction.editReply(response);
    }
  },
};
