import { MessageFlags } from "discord.js"
import type { ChannelSelectMenuInteraction } from "discord.js"
import { generateTwitchEmbed } from "@/utils/twitch"
import type { GuildTwitch } from "@/types/schemas"
import dbGuild from "@/schemas/guild"
import { t } from "@/utils/i18n"

export const id = "twitch_channel"
export async function execute(interaction: ChannelSelectMenuInteraction) {
	const channel = interaction.channels.first()
	if (!channel) return interaction.reply({ content: t(interaction.locale, "common.no_channel_selected"), flags: MessageFlags.Ephemeral })

	const guildProfile = await dbGuild.findOne({ guildId: interaction.guild?.id })
	if (!guildProfile) return interaction.reply({ content: t(interaction.locale, "common.database_not_found"), flags: MessageFlags.Ephemeral })

	const dbData = guildProfile.get("guildTwitch") as GuildTwitch
	dbData.channelId = channel.id

	guildProfile.set("guildTwitch", dbData)
	guildProfile.markModified("guildTwitch")
	await guildProfile.save().catch(console.error)

	// Générer l'embed mis à jour avec la fonction utilitaire
	const { embed, components } = generateTwitchEmbed(dbData, interaction.client, interaction.guild?.id ?? "", interaction.locale)

	// Mettre à jour l'embed original avec les nouvelles données
	return interaction.update({
		content: t(interaction.locale, "common.channel_configured_success") + ` ${t(interaction.locale, "twitch.notifications_sent_to", { channel: `<#${channel.id}>` })}`,
		embeds: [embed],
		components
	})
}
