import type { ButtonInteraction } from 'discord.js';
import { t } from '@nexumi/shared';
import type { BotContext } from '../../types.js';
import { getGuildLocale } from '../../i18n.js';
import {
  BLACKJACK_BUTTON_PREFIX,
  hitBlackjack,
  parseBlackjackButtonCustomId,
  standBlackjack
} from './games.js';
import { EconomyError } from './service.js';

export function isBlackjackButton(customId: string): boolean {
  return customId.startsWith(BLACKJACK_BUTTON_PREFIX);
}

export async function handleBlackjackButton(
  interaction: ButtonInteraction,
  context: BotContext
): Promise<void> {
  const parsed = parseBlackjackButtonCustomId(interaction.customId);
  const locale = await getGuildLocale(context.prisma, interaction.guildId);

  if (!parsed || !interaction.guildId) {
    await interaction.reply({ content: t(locale, 'economy.blackjack.expired'), ephemeral: true });
    return;
  }

  if (interaction.user.id !== parsed.userId) {
    await interaction.reply({ content: t(locale, 'economy.blackjack.notOwner'), ephemeral: true });
    return;
  }

  try {
    if (parsed.action === 'hit') {
      const result = await hitBlackjack(context, parsed.guildId, parsed.userId, locale);
      await interaction.update({ embeds: [result.embed], components: result.components });
      return;
    }

    const result = await standBlackjack(context, parsed.guildId, parsed.userId, locale);
    await interaction.update({ embeds: [result.embed], components: [] });
  } catch (error) {
    if (error instanceof EconomyError && error.code === 'not_found') {
      await interaction.reply({ content: t(locale, 'economy.blackjack.expired'), ephemeral: true });
      return;
    }
    throw error;
  }
}
