// API Route: GET /api/shim/health
// Returns connection pool stats, database health, and system metrics (RAM/CPU/locks)

import type { APIRoute } from 'astro';
import { getPoolStats, getDatabaseStats, getVacuumCandidates } from '@/lib/shim/pool';
import { getSystemHealth } from '@/lib/shim/health';

export const GET: APIRoute = async ({ request }) => {
    try {
        // Token validation
        const authHeader = request.headers.get('Authorization');
        const token = authHeader?.replace('Bearer ', '');

        const godToken = import.meta.env.GOD_MODE_TOKEN;
        if (godToken && token !== godToken) {
            return new Response(JSON.stringify({ error: 'Unauthorized' }), {
                status: 401,
                headers: { 'Content-Type': 'application/json' }
            });
        }

        // Get all health stats
        const poolStats = getPoolStats();
        const dbStats = await getDatabaseStats();
        const vacuumCandidates = await getVacuumCandidates();
        const systemHealth = await getSystemHealth();
        const needsVacuum = vacuumCandidates.length > 0 && vacuumCandidates[0].deadPercent > 20;

        // Overall status (most critical wins)
        const overallStatus =
            systemHealth.status === 'critical' || poolStats.status === 'critical'
                ? 'critical'
                : systemHealth.status === 'warning' || poolStats.status === 'warning'
                    ? 'warning'
                    : 'healthy';

        return new Response(JSON.stringify({
            timestamp: new Date().toISOString(),
            status: overallStatus,
            system: systemHealth,
            pool: poolStats,
            database: dbStats,
            vacuum: {
                recommended: needsVacuum,
                candidates: vacuumCandidates
            },
            alerts: [
                ...systemHealth.alerts,
                ...(poolStats.status !== 'healthy' ? [poolStats.message] : [])
            ]
        }), {
            status: 200,
            headers: { 'Content-Type': 'application/json' }
        });

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