import { Message, TextChannel } from "discord.js";
import { lootdropService } from "@shared/modules/economy/lootdrop.service";
import { getLootdropMessage } from "./lootdrop.view";
import { terminalService } from "@modules/system/terminal.service";

/**
 * Process a Discord message for lootdrop activity tracking.
 * Called from messageCreate event handler.
 */
export async function processLootdropMessage(message: Message): Promise<void> {
    if (message.author.bot || !message.guild) return;

    const { shouldSpawn } = lootdropService.trackActivity(message.channel.id);

    if (shouldSpawn) {
        await spawnLootdrop(message.channel as TextChannel);
    }
}

/**
 * Spawn a lootdrop in a Discord channel.
 * Used by both bot events and API routes.
 */
export async function spawnLootdrop(
    channel: TextChannel,
    overrideReward?: number,
    overrideCurrency?: string
): Promise<void> {
    const { reward, currency } = lootdropService.calculateReward(overrideReward, overrideCurrency);
    const { content, files, components } = await getLootdropMessage(reward, currency);

    try {
        const sentMessage = await channel.send({ content, files, components });
        await lootdropService.persistLootdrop(sentMessage.id, channel.id, reward, currency);
        terminalService.update(channel.guildId);
    } catch (error) {
        console.error("Failed to spawn lootdrop:", error);
    }
}

/**
 * Delete a lootdrop from DB and Discord.
 */
export async function deleteLootdrop(messageId: string): Promise<boolean> {
    const result = await lootdropService.removeLootdrop(messageId);
    if (!result) return false;

    try {
        const { AuroraClient } = await import("@/lib/BotClient");
        const channel = await AuroraClient.channels.fetch(result.channelId) as TextChannel;
        if (channel) {
            const message = await channel.messages.fetch(messageId);
            if (message) await message.delete();
        }
    } catch (e) {
        console.warn("Could not delete lootdrop message from Discord:", e);
    }

    return true;
}
