const { SlashCommandBuilder, EmbedBuilder, PermissionFlagsBits, ChannelType } = require('discord.js');
const { EMBED_COLORS } = require('../utils/modeHelper');

module.exports = {
  data: new SlashCommandBuilder()
    .setName('starboard')
    .setDescription('Configure the starboard system')
    .setDefaultMemberPermissions(PermissionFlagsBits.ManageGuild)
    .addSubcommand(subcommand =>
      subcommand
        .setName('setup')
        .setDescription('Set up or update the starboard channel')
        .addChannelOption(option =>
          option.setName('channel')
            .setDescription('The starboard channel')
            .setRequired(true)
            .addChannelTypes(ChannelType.GuildText)
        )
        .addIntegerOption(option =>
          option.setName('threshold')
            .setDescription('Minimum stars needed (default: 3)')
            .setRequired(false)
            .setMinValue(1)
            .setMaxValue(50)
        )
    )
    .addSubcommand(subcommand =>
      subcommand
        .setName('disable')
        .setDescription('Disable the starboard')
    )
    .addSubcommand(subcommand =>
      subcommand
        .setName('status')
        .setDescription('View current starboard settings')
    ),

  async execute(interaction, supabase, client) {
    const subcommand = interaction.options.getSubcommand();
    const guildId = interaction.guildId;

    if (!supabase) {
      return interaction.reply({ content: 'Starboard system unavailable.', ephemeral: true });
    }

    if (subcommand === 'setup') {
      const channel = interaction.options.getChannel('channel');
      const threshold = interaction.options.getInteger('threshold') || 3;

      await supabase.from('starboard_config').upsert({
        guild_id: guildId,
        channel_id: channel.id,
        threshold: threshold,
        enabled: true,
        updated_at: new Date().toISOString()
      }, { onConflict: 'guild_id' });

      const embed = new EmbedBuilder()
        .setColor(EMBED_COLORS.success)
        .setTitle('⭐ Starboard Configured!')
        .addFields(
          { name: '📍 Channel', value: `${channel}`, inline: true },
          { name: '🎯 Threshold', value: `${threshold} stars`, inline: true }
        )
        .setDescription('Messages that receive enough ⭐ reactions will be posted to the starboard!')
        .setTimestamp();

      await interaction.reply({ embeds: [embed] });
    }

    else if (subcommand === 'disable') {
      await supabase
        .from('starboard_config')
        .update({ enabled: false })
        .eq('guild_id', guildId);

      const embed = new EmbedBuilder()
        .setColor(EMBED_COLORS.warning)
        .setTitle('⭐ Starboard Disabled')
        .setDescription('The starboard has been disabled. Use `/starboard setup` to re-enable.')
        .setTimestamp();

      await interaction.reply({ embeds: [embed] });
    }

    else if (subcommand === 'status') {
      const { data } = await supabase
        .from('starboard_config')
        .select('*')
        .eq('guild_id', guildId)
        .maybeSingle();

      if (!data) {
        return interaction.reply({
          content: 'Starboard is not set up. Use `/starboard setup` to configure it.',
          ephemeral: true
        });
      }

      const embed = new EmbedBuilder()
        .setColor(data.enabled ? EMBED_COLORS.success : EMBED_COLORS.warning)
        .setTitle('⭐ Starboard Status')
        .addFields(
          { name: '📊 Status', value: data.enabled ? '✅ Enabled' : '❌ Disabled', inline: true },
          { name: '📍 Channel', value: `<#${data.channel_id}>`, inline: true },
          { name: '🎯 Threshold', value: `${data.threshold || 3} stars`, inline: true }
        )
        .setTimestamp();

      await interaction.reply({ embeds: [embed] });
    }
  },
};
