import { NextRequest, NextResponse } from 'next/server'
import prisma from '../../../lib/prisma'

// GET /api/offers — optionally filter by businessId
export async function GET(request: NextRequest) {
    try {
        const { searchParams } = new URL(request.url)
        const businessId = searchParams.get('businessId')

        const where: Record<string, unknown> = {}
        if (businessId) where.businessId = businessId

        const offers = await prisma.offer.findMany({
            where,
            include: { business: true },
            orderBy: { createdAt: 'desc' },
        })
        return NextResponse.json(offers)
    } catch (error) {
        console.error('GET /api/offers error:', error)
        return NextResponse.json({ error: 'Erreur serveur' }, { status: 500 })
    }
}

// POST /api/offers
export async function POST(request: NextRequest) {
    try {
        const body = await request.json()
        const offer = await prisma.offer.create({
            data: body,
            include: { business: true },
        })
        return NextResponse.json(offer, { status: 201 })
    } catch (error) {
        console.error('POST /api/offers error:', error)
        return NextResponse.json({ error: 'Erreur lors de la création' }, { status: 500 })
    }
}
