import { MessageFlags, EmbedBuilder } from "discord.js"
import type { ButtonInteraction } from "discord.js"
import type { GuildTwitch } from "@/types/schemas"
import dbGuild from "@/schemas/guild"
import { twitchClient } from "@/utils/twitch"
import { t } from "@/utils/i18n"
import { logConsoleError } from "@/utils/console"

export const id = "twitch_streamer_list"
export async function execute(interaction: ButtonInteraction) {
	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
	if (!dbData.enabled) return interaction.reply({ content: t(interaction.locale, "twitch.module_disabled"), flags: MessageFlags.Ephemeral })
	if (!dbData.streamers.length) {
		const embed = new EmbedBuilder()
			.setTitle(t(interaction.locale, "twitch.list.title"))
			.setDescription(t(interaction.locale, "twitch.list.empty_description"))
			.setColor(0x808080)
			.setTimestamp()

		return interaction.reply({ embeds: [embed], flags: MessageFlags.Ephemeral })
	}

	const streamers = [] as string[]
	await Promise.all(dbData.streamers.map(async (streamer, index) => {
		try {
			const user = await twitchClient.users.getUserById(streamer.twitchUserId)
			if (user) {
				const discordUser = streamer.discordUserId ? `<@${streamer.discordUserId}>` : t(interaction.locale, "twitch.list.discord_not_associated")
				streamers.push(`**${index + 1}.** ${user.displayName}\n└ Discord: ${discordUser}\n└ ID: \`${streamer.twitchUserId}\``)
			} else {
				streamers.push(`**${index + 1}.** ${t(interaction.locale, "twitch.list.user_not_found")}\n└ ID: \`${streamer.twitchUserId}\``)
			}
		} catch (error) {
			logConsoleError('twitch', 'user_fetch_error', { id: streamer.twitchUserId }, error as Error)
			streamers.push(`**${index + 1}.** ${t(interaction.locale, "twitch.list.fetch_error")}\n└ ID: \`${streamer.twitchUserId}\``)
		}
	}))

	const embed = new EmbedBuilder()
		.setTitle(t(interaction.locale, "twitch.list.title"))
		.setDescription(streamers.join("\n\n"))
		.setColor(0x9146FF)
		.setFooter({ text: t(interaction.locale, "twitch.list.footer", { count: streamers.length.toString() }) })
		.setTimestamp()

	return interaction.reply({ embeds: [embed], flags: MessageFlags.Ephemeral })
}
