// API Route: GET /api/shim/sites/list
// Secure endpoint for fetching sites list

import type { APIRoute } from 'astro';
import { getSites } from '@/lib/shim/sites';

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

        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' }
            });
        }

        // Parse query parameters
        const limit = parseInt(url.searchParams.get('limit') || '50');
        const offset = parseInt(url.searchParams.get('offset') || '0');
        const status = url.searchParams.get('status') || undefined;
        const search = url.searchParams.get('search') || undefined;

        // Execute query
        const result = await getSites({ limit, offset, status, search });

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

    } catch (error: any) {
        console.error('API Error [/api/shim/sites/list]:', error);
        return new Response(JSON.stringify({
            error: 'Internal Server Error',
            message: error.message
        }), {
            status: 500,
            headers: { 'Content-Type': 'application/json' }
        });
    }
};
