// API: List posts with filtering
import type { APIRoute } from 'astro';
import { getPosts } from '@/lib/shim/posts';

export const GET: APIRoute = async ({ request }) => {
    try {
        // Token validation
        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' }
            });
        }

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

        const result = await getPosts({ limit, offset, status, siteId, search });

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

    } catch (error: any) {
        console.error('Posts list error:', error);
        return new Response(JSON.stringify({
            error: 'Failed to fetch posts',
            message: error.message
        }), {
            status: 500,
            headers: { 'Content-Type': 'application/json' }
        });
    }
};
