import type { APIRoute } from 'astro';
import { executeCommand } from '@/lib/directus/server';

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

    // We can also accept X-God-Token header for flexibility
    const headerToken = request.headers.get('X-God-Token');

    if (authHeader !== `Bearer ${token}` && headerToken !== token) {
        return new Response(JSON.stringify({ error: 'Unauthorized' }), {
            status: 401,
            headers: { 'Content-Type': 'application/json' }
        });
    }

    try {
        // 2. Parse Command
        const command = await request.json();

        // 3. Execute via Shim
        const data = await executeCommand(command);

        return new Response(JSON.stringify(data), {
            status: 200,
            headers: { 'Content-Type': 'application/json' }
        });

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