import { SlashCommandBuilder, MessageFlags } from "discord.js"
import type { ChatInputCommandInteraction } from "discord.js"
import dbGuild from "@/schemas/guild"
import { t } from "@/utils/i18n"

export const data = new SlashCommandBuilder()
	.setName("locale")
	.setDescription("Manage server language")
	.setDescriptionLocalizations({ fr: "Gérer la langue du serveur" })
	.addStringOption(option => option
		.setName("language")
		.setDescription("Select the server language")
		.setNameLocalizations({ fr: "langue" })
		.setDescriptionLocalizations({ fr: "Sélectionner la langue du serveur" })
		.setRequired(true)
		.addChoices(
			{ name: "Français", value: "fr" },
			{ name: "English", value: "en-US" }
		)
	)

export async function execute(interaction: ChatInputCommandInteraction) {
	const guild = interaction.guild
	if (!guild) return interaction.reply({ content: t(interaction.locale, "common.command_server_only"), flags: MessageFlags.Ephemeral })

	const language = interaction.options.getString("language", true)

	// Récupération du profil du serveur
	const guildProfile = await dbGuild.findOne({ guildId: guild.id })
	if (!guildProfile) return interaction.reply({ content: t(interaction.locale, "common.database_not_found"), flags: MessageFlags.Ephemeral })

	// Sauvegarde de l'ancienne langue pour le message de confirmation
	const oldLocale = guildProfile.guildLocale

	// Mise à jour de la langue
	guildProfile.guildLocale = language
	guildProfile.markModified("guildLocale")
	await guildProfile.save().catch(console.error)

	// Utilisation de la nouvelle langue pour la réponse
	const languageNames = {
		'fr': 'Français',
		'en-US': 'English'
	}

	const oldLanguageName = languageNames[oldLocale as keyof typeof languageNames] || oldLocale
	const newLanguageName = languageNames[language as keyof typeof languageNames] || language

	return interaction.reply({ 
		content: t(language, "locale.updated", { 
			oldLanguage: oldLanguageName, 
			newLanguage: newLanguageName 
		}), 
		flags: MessageFlags.Ephemeral 
	})
}
