import { NextRequest, NextResponse } from 'next/server'; import prisma from '@/lib/prisma'; // GET /api/favorites - Get user's favorites export async function GET(request: NextRequest) { try { const userId = request.headers.get('x-user-id'); if (!userId) { return NextResponse.json({ error: 'Utilisateur non identifié' }, { status: 401 }); } const favorites = await prisma.favorite.findMany({ where: { userId }, include: { business: { include: { categoryRef: true, country: true } } }, orderBy: { createdAt: 'desc' } }); return NextResponse.json(favorites); } catch (error) { console.error('GET /api/favorites error:', error); return NextResponse.json({ error: 'Erreur serveur' }, { status: 500 }); } } // POST /api/favorites - Toggle favorite export async function POST(request: NextRequest) { try { const userId = request.headers.get('x-user-id'); const body = await request.json(); const { businessId } = body; if (!userId) { return NextResponse.json({ error: 'Utilisateur non identifié' }, { status: 401 }); } if (!businessId) { return NextResponse.json({ error: 'businessId requis' }, { status: 400 }); } // Resolve business ID (in case slug was passed) const business = await prisma.business.findFirst({ where: { OR: [ { id: businessId }, { slug: businessId } ] }, select: { id: true } }); if (!business) { return NextResponse.json({ error: 'Entreprise non trouvée' }, { status: 404 }); } const actualBusinessId = business.id; // Check if already favorited const existing = await prisma.favorite.findUnique({ where: { userId_businessId: { userId, businessId: actualBusinessId } } }); if (existing) { // Unfavorite await prisma.favorite.delete({ where: { id: existing.id } }); return NextResponse.json({ favorited: false }); } else { // Favorite await prisma.favorite.create({ data: { userId, businessId: actualBusinessId } }); return NextResponse.json({ favorited: true }); } } catch (error) { console.error('POST /api/favorites error:', error); return NextResponse.json({ error: 'Erreur lors du changement de favori' }, { status: 500 }); } }