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

module.exports = {
  data: new SlashCommandBuilder()
    .setName('modlog')
    .setDescription('View moderation history for a user')
    .setDefaultMemberPermissions(PermissionFlagsBits.ModerateMembers)
    .addUserOption(option =>
      option.setName('user')
        .setDescription('User to check')
        .setRequired(true)
    ),

  async execute(interaction, supabase, client) {
    if (!supabase) {
      return interaction.reply({ content: 'Database not configured.', ephemeral: true });
    }

    const target = interaction.options.getUser('user');
    await interaction.deferReply({ ephemeral: true });

    try {
      const { data: warnings } = await supabase
        .from('warnings')
        .select('*')
        .eq('guild_id', interaction.guildId)
        .eq('user_id', target.id)
        .order('created_at', { ascending: false })
        .limit(10);

      const { data: actions } = await supabase
        .from('mod_actions')
        .select('*')
        .eq('guild_id', interaction.guildId)
        .eq('user_id', target.id)
        .order('created_at', { ascending: false })
        .limit(10);

      const embed = new EmbedBuilder()
        .setColor(0x7c3aed)
        .setTitle(`Moderation Log: ${target.tag}`)
        .setThumbnail(target.displayAvatarURL())
        .setTimestamp();

      if ((!warnings || warnings.length === 0) && (!actions || actions.length === 0)) {
        embed.setDescription('No moderation history found for this user.');
      } else {
        if (warnings && warnings.length > 0) {
          const warnText = warnings.map((w, i) => {
            const date = new Date(w.created_at).toLocaleDateString();
            return `**${i + 1}.** ${w.reason}\n   By: ${w.moderator_tag} | ${date}`;
          }).join('\n\n');
          embed.addFields({ name: `Warnings (${warnings.length})`, value: warnText.slice(0, 1024) });
        }

        if (actions && actions.length > 0) {
          const actionText = actions.map((a, i) => {
            const date = new Date(a.created_at).toLocaleDateString();
            const duration = a.duration_minutes ? ` (${a.duration_minutes}m)` : '';
            return `**${a.action.toUpperCase()}${duration}** - ${a.reason}\n   By: ${a.moderator_tag} | ${date}`;
          }).join('\n\n');
          embed.addFields({ name: `Actions (${actions.length})`, value: actionText.slice(0, 1024) });
        }
      }

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

    } catch (error) {
      console.error('Modlog error:', error);
      await interaction.editReply({ content: 'Failed to fetch moderation log.' });
    }
  },
};
