const { SlashCommandBuilder, EmbedBuilder, PermissionFlagsBits } = require('discord.js');

module.exports = {
  data: new SlashCommandBuilder()
    .setName('warn')
    .setDescription('Warn a user')
    .setDefaultMemberPermissions(PermissionFlagsBits.ModerateMembers)
    .addUserOption(option =>
      option.setName('user')
        .setDescription('User to warn')
        .setRequired(true)
    )
    .addStringOption(option =>
      option.setName('reason')
        .setDescription('Reason for warning')
        .setRequired(true)
        .setMaxLength(500)
    ),

  async execute(interaction, supabase, client) {
    const target = interaction.options.getUser('user');
    const reason = interaction.options.getString('reason');
    const moderator = interaction.user;

    if (target.id === interaction.user.id) {
      return interaction.reply({ content: 'You cannot warn yourself.', ephemeral: true });
    }

    if (target.bot) {
      return interaction.reply({ content: 'You cannot warn bots.', ephemeral: true });
    }

    let warningCount = 1;

    if (supabase) {
      try {
        await supabase.from('warnings').insert({
          guild_id: interaction.guildId,
          user_id: target.id,
          user_tag: target.tag,
          moderator_id: moderator.id,
          moderator_tag: moderator.tag,
          reason: reason,
        });

        const { count } = await supabase
          .from('warnings')
          .select('*', { count: 'exact', head: true })
          .eq('guild_id', interaction.guildId)
          .eq('user_id', target.id);

        warningCount = count || 1;
      } catch (e) {
        console.warn('Failed to save warning:', e.message);
      }
    }

    const embed = new EmbedBuilder()
      .setColor(0xfbbf24)
      .setTitle('User Warned')
      .setThumbnail(target.displayAvatarURL())
      .addFields(
        { name: 'User', value: `${target.tag} (${target.id})`, inline: true },
        { name: 'Moderator', value: moderator.tag, inline: true },
        { name: 'Warning #', value: `${warningCount}`, inline: true },
        { name: 'Reason', value: reason }
      )
      .setTimestamp();

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

    try {
      await target.send({
        embeds: [
          new EmbedBuilder()
            .setColor(0xfbbf24)
            .setTitle(`Warning in ${interaction.guild.name}`)
            .setDescription(`You have been warned by a moderator.`)
            .addFields(
              { name: 'Reason', value: reason },
              { name: 'Warning #', value: `${warningCount}` }
            )
            .setTimestamp()
        ]
      });
    } catch (e) {
      await interaction.followUp({ content: 'Could not DM user about the warning.', ephemeral: true });
    }
  },
};
