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

export default {
  data: new SlashCommandBuilder()
    .setName('fishing')
    .setDescription('Play the fishing mini-game.')
    .setDescriptionLocalizations({
      ko: '낚시 미니게임을 플레이합니다.',
    })
    .addSubcommand((subcommand) =>
      subcommand
        .setName('enter')
        .setDescription('Create or reopen your fishing thread.')
        .setDescriptionLocalizations({
          ko: '낚시 전용 스레드를 생성하거나 다시 엽니다.',
        }),
    )
    .addSubcommand((subcommand) =>
      subcommand
        .setName('cast')
        .setDescription('Start a fishing session inside your fishing thread.')
        .setDescriptionLocalizations({
          ko: '자신의 낚시 스레드 안에서 낚시 세션을 시작합니다.',
        }),
    )
    .addSubcommand((subcommand) =>
      subcommand
        .setName('end')
        .setDescription('End your active fishing session and delete the thread.')
        .setDescriptionLocalizations({
          ko: '진행 중인 낚시 세션을 종료하고 스레드를 삭제합니다.',
        }),
    ),

  async execute(interaction: ChatInputCommandInteraction, locale: SupportedLocale) {
    if (!interaction.guildId) return;

    const config = await prisma.miniGameConfig.findUnique({
      where: { guildId_gameKey: { guildId: interaction.guildId, gameKey: 'fishing' } },
    });
    const subcommand = interaction.options.getSubcommand();

    if (subcommand === 'enter') {
      await interaction.deferReply({ ephemeral: true });

      if (!config || !config.enabled) {
        await interaction.editReply({
          content: t(locale, 'commands.fishing.disabled'),
        });
        return;
      }

      if (config.channelId && config.channelId !== interaction.channelId) {
        await interaction.editReply({
          content: t(locale, 'commands.fishing.restrictedChannel', {
            channel: `<#${config.channelId}>`,
          }),
        });
        return;
      }

      if (!interaction.channel || interaction.channel.type !== ChannelType.GuildText) {
        await interaction.editReply({
          content: t(locale, 'commands.fishing.enterTextChannelOnly'),
        });
        return;
      }

      const result = await FishingService.enterThread(interaction);
      await interaction.editReply({
        content: result.existed
          ? t(locale, 'commands.fishing.enterExistingThread', { thread: `<#${result.thread.id}>` })
          : t(locale, 'commands.fishing.enterCreated', { thread: `<#${result.thread.id}>` }),
      });
      return;
    }

    if (subcommand === 'cast') {
      await interaction.deferReply({ ephemeral: true });

      if (!config || !config.enabled) {
        await interaction.editReply({
          content: t(locale, 'commands.fishing.disabled'),
        });
        return;
      }

      if (!FishingService.isOwnedFishingThread(interaction.channel, interaction.user.username)) {
        await interaction.editReply({
          content: t(locale, 'commands.fishing.castThreadOnly'),
        });
        return;
      }

      const result = await FishingService.startSessionInThread(interaction, locale);
      await interaction.editReply({
        content: result.existed
          ? t(locale, 'commands.fishing.startExistingSession', { thread: `<#${result.thread.id}>` })
          : t(locale, 'commands.fishing.startCreated', { thread: `<#${result.thread.id}>` }),
      });
      return;
    }

    if (subcommand === 'end') {
      await interaction.deferReply({ ephemeral: true });

      const ended = await FishingService.endThreadByUser(interaction, locale);
      if (!ended) {
        await interaction.editReply({
          content: t(locale, 'commands.fishing.noActiveSession'),
        });
        return;
      }

      await interaction.editReply({
        content: t(locale, 'commands.fishing.endDeleted'),
      });
    }
  },
};
