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

module.exports = {
  data: new SlashCommandBuilder()
    .setName('kick')
    .setDescription('Kick a user from the server')
    .setDefaultMemberPermissions(PermissionFlagsBits.KickMembers)
    .addUserOption(option =>
      option.setName('user')
        .setDescription('User to kick')
        .setRequired(true)
    )
    .addStringOption(option =>
      option.setName('reason')
        .setDescription('Reason for kick')
        .setRequired(false)
        .setMaxLength(500)
    ),

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

    const member = await interaction.guild.members.fetch(target.id).catch(() => null);

    if (!member) {
      return interaction.reply({ content: 'User not found in this server.', ephemeral: true });
    }

    if (!member.kickable) {
      return interaction.reply({ content: 'I cannot kick this user. They may have higher permissions.', ephemeral: true });
    }

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

    try {
      await target.send({
        embeds: [
          new EmbedBuilder()
            .setColor(0xff6b6b)
            .setTitle(`Kicked from ${interaction.guild.name}`)
            .addFields({ name: 'Reason', value: reason })
            .setTimestamp()
        ]
      }).catch(() => {});

      await member.kick(reason);

      if (supabase) {
        try {
          await supabase.from('mod_actions').insert({
            guild_id: interaction.guildId,
            action: 'kick',
            user_id: target.id,
            user_tag: target.tag,
            moderator_id: moderator.id,
            moderator_tag: moderator.tag,
            reason: reason,
          });
        } catch (e) {
          console.warn('Failed to log kick:', e.message);
        }
      }

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

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

    } catch (error) {
      console.error('Kick error:', error);
      await interaction.reply({ content: 'Failed to kick user.', ephemeral: true });
    }
  },
};
