import { createCommand } from "@lib/utils";
import { AuroraClient } from "@/lib/BotClient";
import { SlashCommandBuilder, PermissionFlagsBits, EmbedBuilder, Colors } from "discord.js";
import { DrizzleClient } from "@/lib/DrizzleClient";
import { sql } from "drizzle-orm";
import { createBaseEmbed } from "@lib/embeds";

export const health = createCommand({
    data: new SlashCommandBuilder()
        .setName("health")
        .setDescription("Check the bot's health status")
        .setDefaultMemberPermissions(PermissionFlagsBits.Administrator),
    execute: async (interaction) => {
        await interaction.deferReply();

        // 1. Check Discord API latency
        const wsPing = interaction.client.ws.ping;

        // 2. Verify database connection
        let dbStatus = "Connected";
        let dbPing = -1;
        try {
            const start = Date.now();
            await DrizzleClient.execute(sql`SELECT 1`);
            dbPing = Date.now() - start;
        } catch (error) {
            dbStatus = "Disconnected";
            console.error("Health check DB error:", error);
        }

        // 3. Uptime
        const uptime = process.uptime();
        const days = Math.floor(uptime / 86400);
        const hours = Math.floor((uptime % 86400) / 3600);
        const minutes = Math.floor((uptime % 3600) / 60);
        const seconds = Math.floor(uptime % 60);
        const uptimeString = `${days}d ${hours}h ${minutes}m ${seconds}s`;

        // 4. Memory usage
        const memory = process.memoryUsage();
        const heapUsed = (memory.heapUsed / 1024 / 1024).toFixed(2);
        const heapTotal = (memory.heapTotal / 1024 / 1024).toFixed(2);
        const rss = (memory.rss / 1024 / 1024).toFixed(2);

        // 5. Last successful command
        const lastCommand = AuroraClient.lastCommandTimestamp
            ? `<t:${Math.floor(AuroraClient.lastCommandTimestamp / 1000)}:R>`
            : "None since startup";

        const embed = createBaseEmbed("System Health Status", undefined, Colors.Aqua)
            .addFields(
                { name: "📡 Connectivity", value: `**Discord WS:** ${wsPing}ms\n**Database:** ${dbStatus} ${dbPing >= 0 ? `(${dbPing}ms)` : ""}`, inline: true },
                { name: "⏱️ Uptime", value: uptimeString, inline: true },
                { name: "🧠 Memory Usage", value: `**RSS:** ${rss} MB\n**Heap:** ${heapUsed} / ${heapTotal} MB`, inline: false },
                { name: "⌨️ Activity", value: `**Last Command:** ${lastCommand}`, inline: true }
            );

        await interaction.editReply({ embeds: [embed] });
    }
});
