import { createCommand } from "@shared/lib/utils";
import { SlashCommandBuilder, ChannelType, ThreadAutoArchiveDuration, MessageFlags } from "discord.js";
import { tradeService } from "@shared/modules/trade/trade.service";
import { getTradeDashboard } from "@/modules/trade/trade.view";
import { createErrorEmbed, createWarningEmbed } from "@lib/embeds";

export const trade = createCommand({
    data: new SlashCommandBuilder()
        .setName("trade")
        .setDescription("Start a trade with another player")
        .addUserOption(option =>
            option.setName("user")
                .setDescription("The user to trade with")
                .setRequired(true)
        ),
    execute: async (interaction) => {
        const targetUser = interaction.options.getUser("user", true);

        if (targetUser.id === interaction.user.id) {
            await interaction.reply({ embeds: [createWarningEmbed("You cannot trade with yourself.")], flags: MessageFlags.Ephemeral });
            return;
        }

        if (targetUser.bot) {
            await interaction.reply({ embeds: [createWarningEmbed("You cannot trade with bots.")], flags: MessageFlags.Ephemeral });
            return;
        }

        // Create Thread
        const channel = interaction.channel;
        if (!channel || channel.type === ChannelType.DM) {
            await interaction.reply({ embeds: [createErrorEmbed("Cannot start trade in DMs.")], flags: MessageFlags.Ephemeral });
            return;
        }

        // Check if we can create threads
        // Assuming permissions are fine.

        await interaction.reply({ content: `🔄 Setting up trade with ${targetUser}...` });
        const message = await interaction.fetchReply();

        let thread;
        try {
            thread = await message.startThread({
                name: `trade-${interaction.user.username}-${targetUser.username}`,
                autoArchiveDuration: ThreadAutoArchiveDuration.OneHour,
                reason: "Trading Session"
            });
        } catch (e) {
            // Fallback if message threads fail, try channel threads (private preferred)
            // But startThread on message is usually easiest.
            try {
                await message.delete();
            } catch (err) {
                console.error("Failed to delete setup message", err);
            }
            await interaction.followUp({ embeds: [createErrorEmbed("Failed to create trade thread. Check permissions.")], flags: MessageFlags.Ephemeral });
            return;
        }

        // Setup Session
        const session = tradeService.createSession(thread.id,
            { id: interaction.user.id, username: interaction.user.username },
            { id: targetUser.id, username: targetUser.username }
        );

        // Send Dashboard to Thread
        const dashboard = getTradeDashboard(session);

        await thread.send({ content: `${interaction.user} ${targetUser} Welcome to your trading session!`, ...dashboard });

        // Update original reply
        await interaction.editReply({ content: `✅ Trade opened: <#${thread.id}>` });
    }
});
