const { Collection } = require('discord.js');
const Logger = require('./Logger');

class CooldownManager {
    constructor() {
        this.cooldowns = new Collection();
        this.cooldownTimes = {
            subscribe: 5,
            unsubscribe: 5,
            list_subscriptions: 5,
            finduser: 3,
            matchhistory: 3,
            ping: 1
        };
        this.logger = new Logger('CooldownManager');
    }

    checkCooldown(interaction) {
        if (!this.cooldowns.has(interaction.commandName)) {
            this.cooldowns.set(interaction.commandName, new Collection());
        }

        const now = Date.now();
        const timestamps = this.cooldowns.get(interaction.commandName);
        const cooldownAmount = (this.cooldownTimes[interaction.commandName] || 3) * 1000;
        const userKey = `${interaction.user.id}-${interaction.guildId}`;

        if (timestamps.has(userKey)) {
            const expirationTime = timestamps.get(userKey) + cooldownAmount;

            if (now < expirationTime) {
                const timeLeft = (expirationTime - now) / 1000;
                this.logger.debug('Command on cooldown', {
                    command: interaction.commandName,
                    user: interaction.user.tag,
                    timeLeft
                });
                return timeLeft;
            }
        }

        timestamps.set(userKey, now);
        setTimeout(() => timestamps.delete(userKey), cooldownAmount);
        return 0;
    }

    setCooldown(command, seconds) {
        this.cooldownTimes[command] = seconds;
    }
}

module.exports = CooldownManager;