import { PermissionFlagsBits } from 'discord.js';
import { t, tf } from '@nexumi/shared';
import type { SlashCommand } from '../../types.js';
import { getGuildLocale } from '../../i18n.js';
import { requirePermission } from '../../permissions.js';
import { ephemeral } from '../../interaction-reply.js';
import { starboardCommandData } from './command-definitions.js';
import { botCanPostStarboard, getStarboardConfig, updateStarboardConfig } from './service.js';

const starboardCommand: SlashCommand = {
  data: starboardCommandData,
  async execute(interaction, context) {
    const locale = await getGuildLocale(context.prisma, interaction.guildId);
    if (!interaction.inGuild()) {
      await interaction.reply({ content: t(locale, 'generic.guildOnly'), ...ephemeral() });
      return;
    }
    if (!(await requirePermission(interaction, PermissionFlagsBits.ManageGuild, locale))) {
      return;
    }

    const guildId = interaction.guildId!;
    const sub = interaction.options.getSubcommand();

    if (sub === 'setup') {
      const channelOption = interaction.options.getChannel('channel', true);
      const threshold = interaction.options.getInteger('threshold', true);
      const emoji = interaction.options.getString('emoji') ?? '⭐';
      const allowSelfStar = interaction.options.getBoolean('allow_self_star') ?? false;

      const channel = await interaction.guild!.channels.fetch(channelOption.id).catch(() => null);
      const me = interaction.guild!.members.me;
      if (!channel || !me || !botCanPostStarboard(channel, me.id)) {
        await interaction.reply({
          content: t(locale, 'starboard.invalidChannel'),
          ...ephemeral()
        });
        return;
      }

      await updateStarboardConfig(context.prisma, guildId, {
        enabled: true,
        channelId: channel.id,
        emoji,
        threshold,
        allowSelfStar
      });

      await interaction.reply({ content: t(locale, 'starboard.setupDone'), ...ephemeral() });
      return;
    }

    if (sub === 'status') {
      const config = await getStarboardConfig(context.prisma, guildId);
      if (!config.enabled || !config.channelId) {
        await interaction.reply({
          content: t(locale, 'starboard.notConfigured'),
          ...ephemeral()
        });
        return;
      }
      await interaction.reply({
        content: tf(locale, 'starboard.statusLine', {
          channel: `<#${config.channelId}>`,
          emoji: config.emoji,
          threshold: String(config.threshold),
          selfStar: config.allowSelfStar
            ? t(locale, 'starboard.selfStarOn')
            : t(locale, 'starboard.selfStarOff')
        }),
        ...ephemeral()
      });
    }
  }
};

export const starboardCommands: SlashCommand[] = [starboardCommand];
