
import { createCommand } from "@shared/lib/utils";
import { SlashCommandBuilder, MessageFlags } from "discord.js";
import { economyService } from "@shared/modules/economy/economy.service";
import { userService } from "@shared/modules/user/user.service";
import { config } from "@shared/lib/config";
import { createErrorEmbed, createSuccessEmbed } from "@lib/embeds";
import { UserError } from "@shared/lib/errors";

export const pay = createCommand({
    data: new SlashCommandBuilder()
        .setName("pay")
        .setDescription("Transfer Astral Units to another user")
        .addUserOption(option =>
            option.setName("user")
                .setDescription("The user to pay")
                .setRequired(true)
        )
        .addIntegerOption(option =>
            option.setName("amount")
                .setDescription("Amount to transfer")
                .setMinValue(1)
                .setRequired(true)
        ),
    execute: async (interaction) => {
        const targetUser = await userService.getOrCreateUser(interaction.options.getUser("user", true).id, interaction.options.getUser("user", true).username);
        const discordUser = interaction.options.getUser("user", true);

        if (discordUser.bot) {
            await interaction.reply({ embeds: [createErrorEmbed("You cannot send money to bots.")], flags: MessageFlags.Ephemeral });
            return;
        }

        const amount = BigInt(interaction.options.getInteger("amount", true));
        const senderId = interaction.user.id;
        if (!targetUser) {
            await interaction.reply({ embeds: [createErrorEmbed("User not found.")], flags: MessageFlags.Ephemeral });
            return;
        }

        const receiverId = targetUser.id;

        if (amount < config.economy.transfers.minAmount) {
            await interaction.reply({ embeds: [createErrorEmbed(`Amount must be at least ${config.economy.transfers.minAmount}.`)], flags: MessageFlags.Ephemeral });
            return;
        }

        if (senderId === receiverId.toString()) {
            await interaction.reply({ embeds: [createErrorEmbed("You cannot pay yourself.")], flags: MessageFlags.Ephemeral });
            return;
        }

        try {
            await interaction.deferReply();
            await economyService.transfer(senderId, receiverId.toString(), amount);

            const embed = createSuccessEmbed(`Successfully sent ** ${amount}** Astral Units to <@${targetUser.id}>.`, "💸 Transfer Successful");
            await interaction.editReply({ embeds: [embed], content: `<@${receiverId}>` });

        } catch (error: any) {
            if (error instanceof UserError) {
                await interaction.editReply({ embeds: [createErrorEmbed(error.message)] });
            } else {
                console.error("Error sending payment:", error);
                await interaction.editReply({ embeds: [createErrorEmbed("An unexpected error occurred.")] });
            }
        }
    }
});
