const { EmbedBuilder } = require('discord.js');
const { createClient } = require('@supabase/supabase-js');

let supabase = null;
if (process.env.SUPABASE_URL && process.env.SUPABASE_SERVICE_ROLE) {
  supabase = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_SERVICE_ROLE);
}

const starboardCache = new Map();
const STAR_EMOJI = '⭐';
const DEFAULT_THRESHOLD = 3;

async function getStarboardConfig(guildId) {
  if (!supabase) return null;
  
  const cached = starboardCache.get(guildId);
  if (cached && Date.now() - cached.timestamp < 60000) {
    return cached.config;
  }

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

    starboardCache.set(guildId, { config: data, timestamp: Date.now() });
    return data;
  } catch (e) {
    return null;
  }
}

async function handleStarboard(reaction, user) {
  if (reaction.emoji.name !== STAR_EMOJI) return;
  if (reaction.message.author?.bot) return;

  const guildId = reaction.message.guildId;
  const config = await getStarboardConfig(guildId);
  
  if (!config || !config.enabled || !config.channel_id) return;

  const threshold = config.threshold || DEFAULT_THRESHOLD;
  const starCount = reaction.count;

  if (starCount < threshold) return;

  const message = reaction.message;
  const starboardChannel = message.guild.channels.cache.get(config.channel_id);
  
  if (!starboardChannel) return;

  try {
    const { data: existing } = await supabase
      .from('starboard_messages')
      .select('starboard_message_id')
      .eq('original_message_id', message.id)
      .maybeSingle();

    const embed = new EmbedBuilder()
      .setColor(0xFFD700)
      .setAuthor({
        name: message.author.tag,
        iconURL: message.author.displayAvatarURL({ size: 128 })
      })
      .setDescription(message.content || '*No text content*')
      .addFields(
        { name: '📍 Source', value: `[Jump to message](${message.url})`, inline: true },
        { name: '⭐ Stars', value: `${starCount}`, inline: true }
      )
      .setTimestamp(message.createdAt)
      .setFooter({ text: `#${message.channel.name}` });

    if (message.attachments.size > 0) {
      const attachment = message.attachments.first();
      if (attachment.contentType?.startsWith('image/')) {
        embed.setImage(attachment.url);
      }
    }

    const starEmoji = starCount >= 10 ? '🌟' : starCount >= 5 ? '✨' : '⭐';
    const content = `${starEmoji} **${starCount}** | <#${message.channelId}>`;

    if (existing?.starboard_message_id) {
      try {
        const starboardMessage = await starboardChannel.messages.fetch(existing.starboard_message_id);
        await starboardMessage.edit({ content, embeds: [embed] });
      } catch (e) {}
    } else {
      const starboardMessage = await starboardChannel.send({ content, embeds: [embed] });
      
      await supabase.from('starboard_messages').insert({
        guild_id: guildId,
        original_message_id: message.id,
        starboard_message_id: starboardMessage.id,
        channel_id: message.channelId,
        author_id: message.author.id,
        star_count: starCount
      });
    }

    if (existing) {
      await supabase
        .from('starboard_messages')
        .update({ star_count: starCount })
        .eq('original_message_id', message.id);
    }
  } catch (e) {
    console.error('[Starboard] Error:', e.message);
  }
}

module.exports = {
  name: 'messageReactionAdd',
  async execute(reaction, user, client) {
    if (reaction.partial) {
      try {
        await reaction.fetch();
      } catch (e) {
        return;
      }
    }

    await handleStarboard(reaction, user);
  }
};
