import { NextResponse } from 'next/server';
import { searchMarketplaceProducts } from '@/lib/marketplace-data';

export async function GET(request: Request) {
  try {
    const { searchParams } = new URL(request.url);
    const q = searchParams.get('q');

    if (!q || q.trim() === '') {
      return NextResponse.json({ products: [] });
    }

    const products = await searchMarketplaceProducts({ q, limit: 5 });

    return NextResponse.json({
      products: products.map(p => ({
        id: p.id,
        name: p.name,
        image_url: p.product_images?.find(img => img.is_primary)?.image_url || p.image_url,
        price: p.price,
        store_name: p.store?.name || 'Loja',
        slug: p.store?.slug || ''
      }))
    });
  } catch (error) {
    console.error('Error fetching search suggestions:', error);
    return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
  }
}
