const { SlashCommandBuilder } = require('discord.js');
const db = require('../database');

const verifyMvcCommand = new SlashCommandBuilder()
    .setName('verify-mvc')
    .setDescription('Verify your ModpackChecker purchase')
    .addStringOption(option =>
        option.setName('order_id')
            .setDescription('Your BuiltByBit order ID')
            .setRequired(true)
    );

async function handleVerifyMvcCommand(interaction) {
    await interaction.deferReply({ ephemeral: true });

    const orderId = interaction.options.getString('order_id').toUpperCase().trim();
    const discordId = interaction.user.id;
    const roleId = process.env.MVC_CUSTOMER_ROLE_ID;

    if (!roleId || roleId === 'TBD') {
        return interaction.editReply('❌ Customer role not configured yet. Please contact an admin.');
    }

    try {
        // Find the license
        const { rows } = await db.query(
            'SELECT * FROM mvc_licenses WHERE order_id = $1',
            [orderId]
        );

        if (rows.length === 0) {
            return interaction.editReply('❌ No license found for that order ID. Double-check your BuiltByBit order number.');
        }

        const license = rows[0];

        if (license.status !== 'active') {
            return interaction.editReply(`❌ That license is **${license.status}**. Contact support if this is unexpected.`);
        }

        // Check if already claimed by someone else
        if (license.discord_id && license.discord_id !== discordId) {
            return interaction.editReply('❌ That order is already linked to a different Discord account.');
        }

        // Link discord_id to license
        await db.query(
            'UPDATE mvc_licenses SET discord_id = $1 WHERE id = $2',
            [discordId, license.id]
        );

        // Assign customer role
        const guild = interaction.guild;
        const member = await guild.members.fetch(discordId);
        await member.roles.add(roleId);

        const tierLabel = license.tier === 'professional' ? '⭐ Professional' : 'Standard';
        console.log(`🔑 [MVC Verify] ${interaction.user.tag} verified order ${orderId} (${license.tier})`);

        return interaction.editReply(
            `✅ Verified! You now have the **ModpackChecker Customer** role.\n` +
            `**Tier:** ${tierLabel}\n` +
            `**Order:** ${orderId}`
        );

    } catch (error) {
        console.error('❌ [MVC Verify] Error:', error);
        return interaction.editReply('❌ An error occurred during verification. Please try again or contact support.');
    }
}

module.exports = { verifyMvcCommand, handleVerifyMvcCommand };
