import { SlashCommandBuilder, ChatInputCommandInteraction } from 'discord.js';
import { prisma } from '../database';
import { t, SupportedLocale, SUPPORTED_LOCALES } from '../i18n';

export default {
  data: new SlashCommandBuilder()
    .setName('language')
    .setDescription('Set your personal language for the bot.')
    .setDescriptionLocalizations({
      ko: '봇의 개인 사용 언어를 설정합니다.',
    })
    .addStringOption(option =>
      option.setName('locale')
        .setDescription('Language to use')
        .setDescriptionLocalizations({
          ko: '사용할 언어',
        })
        .setRequired(true)
        .addChoices(
          { name: 'English', value: 'en' },
          { name: '한국어', value: 'ko' },
        )
    ),

  async execute(interaction: ChatInputCommandInteraction, locale: SupportedLocale) {
    const newLocale = interaction.options.getString('locale', true) as SupportedLocale;

    // Validate locale (safety check)
    if (!SUPPORTED_LOCALES.includes(newLocale)) {
      await interaction.editReply({ content: `Unsupported locale: ${newLocale}` });
      return;
    }

    await prisma.userLocale.upsert({
      where: { userId: interaction.user.id },
      update: { locale: newLocale },
      create: { userId: interaction.user.id, locale: newLocale },
    });

    // Respond in the NEWLY selected locale
    await interaction.editReply({
      content: t(newLocale, 'commands.language.userSet', { locale: newLocale === 'ko' ? '한국어' : 'English' }),
    });
  },
};

