import { NextResponse, NextRequest } from 'next/server';
import { cookies } from 'next/headers';
import { generateProductsForCategory } from './data';
import { productCategoriesData } from '../../data';

export async function GET(request: NextRequest, context: any) {
  const cookieStore = await cookies();
  const lang = cookieStore.get('locale')?.value || 'en';

  const params = await context.params;
  const category = productCategoriesData.find((cat) => cat.id === params.id);

  if (!category) {
    return NextResponse.json({ error: 'Not found' }, { status: 404 });
  }

  const { searchParams } = new URL(request.url);
  const page = parseInt(searchParams.get('page') || '1', 10);
  const perPage = 5;

  const allProducts = generateProductsForCategory(category.id);
  const start = (page - 1) * perPage;
  const end = start + perPage;
  const paginatedProducts = allProducts.slice(start, end);

  return NextResponse.json({
    data: paginatedProducts,
    pagination: {
      page,
      perPage,
      total: allProducts.length,
      totalPages: Math.ceil(allProducts.length / perPage),
    },
  });
}
