const { SlashCommandBuilder } = require('discord.js');
const db = require('../database');
const { validateMinecraftUser } = require('../mojang/validate');
const { triggerImmediateSync } = require('../sync/immediate');

const linkCommand = new SlashCommandBuilder()
  .setName('link')
  .setDescription('Link your Minecraft account')
  .addStringOption(option =>
    option.setName('username')
      .setDescription('Your exact Minecraft username')
      .setRequired(true)
  );

async function handleLinkCommand(interaction) {
  await interaction.deferReply({ ephemeral: true });
  const username = interaction.options.getString('username');
  const discordId = interaction.user.id;

  const mojangData = await validateMinecraftUser(username);
  if (!mojangData) {
    return interaction.editReply(`❌ Could not find account **${username}**.`);
  }

  try {
    await db.query(
      `INSERT INTO users (discord_id, minecraft_username, minecraft_uuid) 
       VALUES ($1, $2, $3) 
       ON CONFLICT (discord_id) 
       DO UPDATE SET minecraft_username = $2, minecraft_uuid = $3`,
      [discordId, mojangData.name, mojangData.uuid]
    );

    await interaction.editReply(`✅ Linked **${mojangData.name}**! Syncing whitelists...`);
    triggerImmediateSync();
  } catch (error) {
    console.error("Database error:", error);
    interaction.editReply('❌ An internal error occurred.');
  }
}

module.exports = { linkCommand, handleLinkCommand };
