import { PermissionFlagsBits } from 'discord.js';
import { t } from '@nexumi/shared';
import type { SlashCommand } from '../../types.js';
import { getGuildLocale } from '../../i18n.js';
import { requirePermission } from '../../permissions.js';
import { starboardCommandData } from './command-definitions.js';
import { 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: true });
      return;
    }
    if (!(await requirePermission(interaction, PermissionFlagsBits.ManageGuild, locale))) {
      return;
    }

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

    if (sub === 'setup') {
      const channel = 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;

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

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

    const config = await getStarboardConfig(context.prisma, guildId);
    if (!config.enabled || !config.channelId) {
      await interaction.reply({ content: t(locale, 'starboard.notConfigured'), ephemeral: true });
    }
  }
};

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