import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { localeSchema } from '@/lib/validation';

export async function GET(req: Request) {
  const { searchParams } = new URL(req.url);
  const localeParsed = localeSchema.safeParse(searchParams.get('locale') ?? 'fr');
  const locale = localeParsed.success ? localeParsed.data : 'fr';
  const category = searchParams.get('category');
  const q = searchParams.get('q');

  const products = await prisma.product.findMany({
    where: {
      published: true,
      ...(category ? { category: { slug: category } } : {}),
      ...(q
        ? { translations: { some: { locale, name: { contains: q, mode: 'insensitive' } } } }
        : {})
    },
    include: { translations: { where: { locale } } },
    orderBy: { createdAt: 'desc' }
  });

  return NextResponse.json(
    products
      .filter((p) => p.translations[0])
      .map((p) => ({
        id: p.id,
        slug: p.slug,
        sku: p.sku,
        price: p.price ? Number(p.price) : null,
        currency: p.currency,
        available: p.available,
        image: p.images[0] ?? null,
        name: p.translations[0].name,
        shortDescription: p.translations[0].shortDescription
      }))
  );
}
