import type { APIRoute } from 'astro';
import { getProductsByCategory } from '../../../../lib/categories/category-manager.js';

export const GET: APIRoute = async ({ params, url }) => {
  try {
    const slug = params.slug!;
    const page = parseInt(url.searchParams.get('page') || '1');
    const limit = parseInt(url.searchParams.get('limit') || '24');
    const sort = url.searchParams.get('sort') || 'newest';

    const result = await getProductsByCategory(slug, { page, limit, sort });
    return new Response(JSON.stringify(result), {
      headers: { 'Content-Type': 'application/json' },
    });
  } catch (e: any) {
    return new Response(JSON.stringify({ error: e.message }), { status: 500 });
  }
};
