import { Events, EmbedBuilder, ChannelType } from "discord.js"
import type { GuildMember } from "discord.js"
import { t, getGuildLocale } from "@/utils/i18n"
import { logConsole } from "@/utils/console"

export const name = Events.GuildMemberUpdate
export async function execute(oldMember: GuildMember, newMember: GuildMember) {
	if (newMember.guild.id === "796327643783626782") {
		// Jujul Community
		const guild = newMember.guild

		const channel = await guild.channels.fetch("924353449930412153")
		if (!channel || (channel.type !== ChannelType.GuildText && channel.type !== ChannelType.GuildAnnouncement)) {
			logConsole('discordjs', 'boost.no_channel', { channelId: "924353449930412153" })
			return
		}

		const boostRole = guild.roles.premiumSubscriberRole
		if (!boostRole) { logConsole('discordjs', 'boost.no_boost_role'); return }

		const hadRole = oldMember.roles.cache.find(role => role.id === boostRole.id)
		const hasRole = newMember.roles.cache.find(role => role.id === boostRole.id)

		if (!hadRole && hasRole) {
			if (!guild.members.me) { logConsole('discordjs', 'boost.not_in_guild'); return }

			const guildLocale = await getGuildLocale(guild.id)
			const embed = new EmbedBuilder()
				.setColor(guild.members.me.displayHexColor)
				.setTitle(t(guildLocale, "boost.new_boost_title", { username: newMember.user.username }))
				.setDescription(t(guildLocale, "boost.new_boost_description", { count: guild.premiumSubscriptionCount?.toString() ?? "0" }))
				.setThumbnail(newMember.user.avatarURL())
				.setTimestamp(new Date())

			return channel.send({ embeds: [embed] })
		}
	}
}
