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

export { isSuggestionVoteButton as isSuggestionButton } from './service.js';

function parseSuggestionVoteButton(
  customId: string
): { suggestionId: string; direction: 'up' | 'down' } | null {
  if (!customId.startsWith(SUGGESTION_VOTE_PREFIX)) {
    return null;
  }
  const rest = customId.slice(SUGGESTION_VOTE_PREFIX.length);
  const lastColon = rest.lastIndexOf(':');
  if (lastColon === -1) {
    return null;
  }
  const suggestionId = rest.slice(0, lastColon);
  const direction = rest.slice(lastColon + 1);
  if (!suggestionId || (direction !== 'up' && direction !== 'down')) {
    return null;
  }
  return { suggestionId, direction };
}

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

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

  try {
    await applySuggestionVote(context, parsed.suggestionId, interaction.user.id, parsed.direction, locale);
    await interaction.reply({
      content: t(locale, parsed.direction === 'up' ? 'suggestion.votedUp' : 'suggestion.votedDown'),
      ephemeral: true
    });
  } catch (error) {
    if (error instanceof SuggestionError) {
      await interaction.reply({
        content: t(locale, `suggestion.error.${error.code}`),
        ephemeral: true
      });
      return;
    }
    throw error;
  }
}
