import { EmbedBuilder, MessageFlags } from "discord.js"
import type { ButtonInteraction } from "discord.js"
import crypto from "crypto"
import * as Freebox from "@/utils/freebox"
import type { APIResponseData, APIResponseDataError, APIResponseDataVersion, ConnectionStatus, GetChallenge, OpenSession } from "@/types/freebox"
import type { GuildFbx } from "@/types/schemas"
import dbGuild from "@/schemas/guild"
import { t } from "@/utils/i18n"
import { logConsoleError } from "@/utils/console"

export const id = "freebox_test_connection"
export async function execute(interaction: ButtonInteraction) {
	await interaction.deferReply({ flags: MessageFlags.Ephemeral })

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

	const dbData = guildProfile.get("guildFbx") as GuildFbx
	if (!dbData.enabled || !dbData.host || !dbData.appToken) {
		return interaction.followUp({ content: t(interaction.locale, "freebox.general.incomplete_configuration"), flags: MessageFlags.Ephemeral })
	}

	try {
		// Test de la version API
		const versionData = await Freebox.Core.Version(dbData.host) as APIResponseDataVersion

		// Test d'authentification
		const challengeData = await Freebox.Login.Challenge(dbData.host) as APIResponseData<GetChallenge>
		if (!challengeData.success) return await Freebox.handleError(challengeData as APIResponseDataError, interaction, false)

		const password = crypto.createHmac("sha1", dbData.appToken).update(challengeData.result.challenge).digest("hex")
		const sessionData = await Freebox.Login.Session(dbData.host, password) as APIResponseData<OpenSession>
		if (!sessionData.success) return await Freebox.handleError(sessionData as APIResponseDataError, interaction, false)

		const sessionToken = sessionData.result.session_token
		if (!sessionToken) return await interaction.followUp({ content: t(interaction.locale, "freebox.auth.session_token_failed"), flags: MessageFlags.Ephemeral })

		// Test de la connexion
		const connectionData = await Freebox.Get.Connection(dbData.host, sessionToken) as APIResponseData<ConnectionStatus>
		if (!connectionData.success) return await Freebox.handleError(connectionData as APIResponseDataError, interaction, false)

		// Création de l'embed de succès
		const embed = new EmbedBuilder()
			.setTitle(t(interaction.locale, "freebox.test.connection_success_title"))
			.setColor(0x00ff00)
			.addFields(
				{
					name: t(interaction.locale, "freebox.test.api_field"),
					value: t(interaction.locale, "freebox.test.api_version", { version: versionData.api_version }),
					inline: true
				},
				{
					name: t(interaction.locale, "freebox.test.auth_field"),
					value: t(interaction.locale, "freebox.test.token_valid"),
					inline: true
				},
				{
					name: t(interaction.locale, "freebox.test.connection_field"),
					value: connectionData.result.state === "up" ? 
						t(interaction.locale, "freebox.test.connection_active") : 
						t(interaction.locale, "freebox.test.connection_inactive"),
					inline: true
				}
			)
			.setTimestamp()

		return await interaction.followUp({ embeds: [embed], flags: MessageFlags.Ephemeral })
	} catch (error) {
		logConsoleError('freebox', 'test_connection_error', undefined, error as Error)
		return interaction.followUp({ content: t(interaction.locale, "freebox.test.connection_error"), flags: MessageFlags.Ephemeral })
	}
}
