import type { APIRoute } from 'astro';
import { pool } from '@/lib/db';

/**
 * Connection Pool Statistics
 * Monitor database connection saturation
 */

function validateGodToken(request: Request): boolean {
    const token = request.headers.get('X-God-Token') ||
        request.headers.get('Authorization')?.replace('Bearer ', '') ||
        new URL(request.url).searchParams.get('token');

    const godToken = process.env.GOD_MODE_TOKEN || import.meta.env.GOD_MODE_TOKEN;
    if (!godToken) return true;
    return token === godToken;
}

export const GET: APIRoute = async ({ request }) => {
    if (!validateGodToken(request)) {
        return new Response(JSON.stringify({ error: 'Unauthorized' }), {
            status: 401,
            headers: { 'Content-Type': 'application/json' }
        });
    }

    try {
        // Get pool stats
        const totalCount = pool.totalCount;
        const idleCount = pool.idleCount;
        const waitingCount = pool.waitingCount;

        // Calculate saturation
        const saturation_pct = totalCount > 0
            ? Math.round(((totalCount - idleCount) / totalCount) * 100 * 10) / 10
            : 0;

        // Get active connections from database
        const activeConnections = await pool.query(`
            SELECT 
                count(*) FILTER (WHERE state = 'active') as active,
                count(*) FILTER (WHERE state = 'idle') as idle,
                count(*) FILTER (WHERE state = 'idle in transaction') as idle_in_transaction,
                count(*) as total
            FROM pg_stat_activity
            WHERE datname = current_database()
        `);

        const connStats = activeConnections.rows[0];

        return new Response(JSON.stringify({
            pool: {
                total: totalCount,
                idle: idleCount,
                waiting: waitingCount,
                active: totalCount - idleCount,
                saturation_pct
            },
            database: {
                active: parseInt(connStats.active),
                idle: parseInt(connStats.idle),
                idle_in_transaction: parseInt(connStats.idle_in_transaction),
                total: parseInt(connStats.total)
            },
            health: {
                status: saturation_pct > 90 ? '⚠️ CRITICAL' : saturation_pct > 75 ? '⚠️ WARNING' : '✅ HEALTHY',
                recommendation: saturation_pct > 90
                    ? 'Increase pool size or kill stuck queries'
                    : saturation_pct > 75
                        ? 'Monitor closely, consider throttling'
                        : 'Pool operating normally'
            },
            timestamp: new Date().toISOString()
        }), {
            status: 200,
            headers: { 'Content-Type': 'application/json' }
        });

    } catch (error: any) {
        return new Response(JSON.stringify({
            error: error.message
        }), {
            status: 500,
            headers: { 'Content-Type': 'application/json' }
        });
    }
};
