import type { APIRoute } from 'astro';
import { killLocks, vacuumAnalyze, getTableBloat } from '@/lib/db/mechanic';

/**
 * Mechanic Execute Endpoint
 * Manual trigger for maintenance operations
 */

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 POST: APIRoute = async ({ request }) => {
    if (!validateGodToken(request)) {
        return new Response(JSON.stringify({ error: 'Unauthorized' }), {
            status: 401,
            headers: { 'Content-Type': 'application/json' }
        });
    }

    try {
        const { action, table } = await request.json();

        if (!action) {
            return new Response(JSON.stringify({
                error: 'Missing action',
                valid_actions: ['kill-locks', 'vacuum', 'analyze-bloat']
            }), {
                status: 400,
                headers: { 'Content-Type': 'application/json' }
            });
        }

        let result: any;

        switch (action) {
            case 'kill-locks':
                const killed = await killLocks();
                result = {
                    action: 'kill-locks',
                    processes_terminated: killed,
                    message: `Killed ${killed} stuck queries`
                };
                break;

            case 'vacuum':
                await vacuumAnalyze(table);
                result = {
                    action: 'vacuum',
                    table: table || 'all',
                    message: `VACUUM ANALYZE completed${table ? ` on ${table}` : ''}`
                };
                break;

            case 'analyze-bloat':
                const bloat = await getTableBloat();
                result = {
                    action: 'analyze-bloat',
                    tables: bloat,
                    message: `Found ${bloat.length} tables with bloat`
                };
                break;

            default:
                return new Response(JSON.stringify({
                    error: `Unknown action: ${action}`
                }), {
                    status: 400,
                    headers: { 'Content-Type': 'application/json' }
                });
        }

        return new Response(JSON.stringify({
            success: true,
            ...result,
            timestamp: new Date().toISOString()
        }), {
            status: 200,
            headers: { 'Content-Type': 'application/json' }
        });

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

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

    return new Response(JSON.stringify({
        endpoint: 'POST /api/god/mechanic/execute',
        description: 'Manual database maintenance operations',
        actions: {
            'kill-locks': 'Terminate stuck queries (>30s)',
            'vacuum': 'Run VACUUM ANALYZE (specify table or all)',
            'analyze-bloat': 'Get tables with dead row bloat'
        },
        usage: {
            kill_locks: { action: 'kill-locks' },
            vacuum_all: { action: 'vacuum' },
            vacuum_table: { action: 'vacuum', table: 'posts' },
            check_bloat: { action: 'analyze-bloat' }
        }
    }, null, 2), {
        status: 200,
        headers: { 'Content-Type': 'application/json' }
    });
};
