import type { ButtonInteraction } from 'discord.js';
import { t } from '@nexumi/shared';
import type { BotContext } from '../../types.js';
import { getGuildLocale } from '../../i18n.js';
import { GiveawayError, joinGiveaway } from './service.js';

export const GIVEAWAY_JOIN_PREFIX = 'gw:join:';

export function joinButtonId(giveawayId: string): string {
  return `${GIVEAWAY_JOIN_PREFIX}${giveawayId}`;
}

export function isGiveawayButton(customId: string): boolean {
  return customId.startsWith(GIVEAWAY_JOIN_PREFIX);
}

export async function handleGiveawayButton(
  interaction: ButtonInteraction,
  context: BotContext
): Promise<void> {
  const locale = await getGuildLocale(context.prisma, interaction.guildId);
  const giveawayId = interaction.customId.slice(GIVEAWAY_JOIN_PREFIX.length);

  if (!giveawayId || !interaction.guildId) {
    await interaction.reply({ content: t(locale, 'giveaway.error.not_found'), ephemeral: true });
    return;
  }

  try {
    await joinGiveaway(context, giveawayId, interaction.user.id, locale);
    await interaction.reply({ content: t(locale, 'giveaway.joined'), ephemeral: true });
  } catch (error) {
    if (error instanceof GiveawayError) {
      await interaction.reply({
        content: t(locale, `giveaway.error.${error.code}`),
        ephemeral: true
      });
      return;
    }
    throw error;
  }
}
