// EMERGENCY API: Kill stuck database locks
// USE WITH CAUTION - Terminates blocking queries

import type { APIRoute } from 'astro';
import { killStuckLocks, getBlockingQueries } from '@/lib/shim/health';

export const POST: APIRoute = async ({ request }) => {
    try {
        // STRICT token validation - this is destructive
        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 list of what will be killed before killing
        const blocking = await getBlockingQueries();

        // Execute kill
        const killedCount = await killStuckLocks();

        console.warn(`[EMERGENCY] Killed ${killedCount} stuck locks`, { blocking });

        return new Response(JSON.stringify({
            success: true,
            killedCount,
            blockedQueries: blocking.length,
            message: `Terminated ${killedCount} blocking queries`
        }), {
            status: 200,
            headers: { 'Content-Type': 'application/json' }
        });

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