import { MessageFlags } from "discord.js"
import type { StringSelectMenuInteraction } from "discord.js"
import { twitchClient } from "@/utils/twitch"
import type { GuildTwitch } from "@/types/schemas"
import dbGuild from "@/schemas/guild"
import { t } from "@/utils/i18n"
import { logConsole } from "@/utils/console"

export const id = "twitch_streamer_remove"
export async function execute(interaction: StringSelectMenuInteraction) {
	const twitchUserId = interaction.values[0]
	if (!twitchUserId) return interaction.reply({ content: t(interaction.locale, "twitch.no_streamer_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

	// Trouver et supprimer le streamer
	const streamerIndex = dbData.streamers.findIndex(s => s.twitchUserId === twitchUserId)
	if (streamerIndex === -1) return interaction.reply({ content: t(interaction.locale, "twitch.streamer_not_found_list"), flags: MessageFlags.Ephemeral })

	// Récupérer le nom du streamer avant suppression
	let streamerName = `ID: ${twitchUserId}`
	try {
		const user = await twitchClient.users.getUserById(twitchUserId)
		if (user) streamerName = user.displayName
	} catch {
		logConsole('twitch', 'user_fetch_error', { id: twitchUserId })
	}

	// Supprimer le streamer
	dbData.streamers.splice(streamerIndex, 1)
	guildProfile.set("guildTwitch", dbData)
	guildProfile.markModified("guildTwitch")
	await guildProfile.save().catch(console.error)

	// Vérifier s'il faut supprimer les listeners
	if (!await dbGuild.exists({ "guildTwitch.streamers.twitchUserId": twitchUserId })) {
		try {
			const userSubs = await twitchClient.eventSub.getSubscriptionsForUser(twitchUserId)
			await Promise.all(userSubs.data.map(async sub => {
				if (sub.transportMethod === "webhook" && (sub.type === "stream.online" || sub.type === "stream.offline")) await sub.unsubscribe()
			}))
			logConsole('twitch', 'listener_removed', { name: streamerName, id: twitchUserId })
		} catch {
			logConsole('twitch', 'listener_removal_error', { streamerName })
		}
	}

	return interaction.update({ content: t(interaction.locale, "twitch.streamer_removed_success", { streamer: streamerName }), components: [] })
}
