import { AuroraClient } from "./BotClient";
import type { ClientStats } from "@shared/modules/dashboard/dashboard.types";

// Cache for client stats (30 second TTL)
let cachedStats: ClientStats | null = null;
let lastFetchTime: number = 0;
const CACHE_TTL_MS = 30 * 1000; // 30 seconds

/**
 * Get Discord client statistics with caching
 * Respects rate limits by caching for 30 seconds
 */
export function getClientStats(): ClientStats {
    const now = Date.now();

    // Return cached stats if still valid
    if (cachedStats && (now - lastFetchTime) < CACHE_TTL_MS) {
        return cachedStats;
    }

    // Fetch fresh stats
    const stats: ClientStats = {
        bot: {
            name: AuroraClient.user?.username || "Aurora",
            avatarUrl: AuroraClient.user?.displayAvatarURL() || null,
            status: AuroraClient.user?.presence.activities[0]?.state || AuroraClient.user?.presence.activities[0]?.name || null,
        },
        guilds: AuroraClient.guilds.cache.size,
        ping: AuroraClient.ws.ping,
        cachedUsers: AuroraClient.users.cache.size,
        commandsRegistered: AuroraClient.commands.size,
        commandsKnown: AuroraClient.knownCommands.size,
        uptime: process.uptime(),
        lastCommandTimestamp: AuroraClient.lastCommandTimestamp,
    };

    // Update cache
    cachedStats = stats;
    lastFetchTime = now;

    return stats;
}

/**
 * Clear the stats cache (useful for testing)
 */
export function clearStatsCache(): void {
    cachedStats = null;
    lastFetchTime = 0;
}
