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

export const POST: APIRoute = async ({ request }) => {
    // 1. Security Check (The Token)
    const authHeader = request.headers.get('Authorization');
    const token = import.meta.env.GOD_MODE_TOKEN || process.env.GOD_MODE_TOKEN;

    // Allow either Bearer token or exact match (for flexibility)
    if (authHeader !== `Bearer ${token}` && request.headers.get('X-God-Token') !== token) {
        return new Response('Unauthorized: You are not God.', { status: 401 });
    }

    // 2. Parse the Command
    const body = await request.json();
    const op = body.operation; // 'vacuum', 'reindex', 'kill_locks'

    try {
        let result = '';

        // 3. Execute the Mechanic
        switch (op) {
            case 'vacuum':
                result = await MECHANIC_OPS.maintenance.vacuum();
                break;
            case 'reindex':
                result = await MECHANIC_OPS.maintenance.reindex();
                break;
            case 'kill_locks':
                result = await MECHANIC_OPS.maintenance.kill_locks();
                break;
            default:
                return new Response('Unknown Operation', { status: 400 });
        }

        // 4. Return Success
        return new Response(result, { status: 200 });

    } catch (error) {
        return new Response(`Error: ${(error as Error).message}`, { status: 500 });
    }
};
