Files
afrov2/app/api/businesses/[id]/route.ts
2026-04-18 22:10:19 +02:00

100 lines
3.2 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server'
import prisma from '@/lib/prisma'
type Params = { params: Promise<{ id: string }> }
// GET /api/businesses/[id]
export async function GET(
_request: NextRequest,
context: { params: Promise<{ id: string }> }
): Promise<Response> {
try {
const { id } = await context.params
const business = await prisma.business.findFirst({
where: {
OR: [
{ id: id },
{ slug: id }
]
},
include: { owner: true, offers: true },
})
if (!business) return NextResponse.json({ error: 'Non trouvé' }, { status: 404 })
return NextResponse.json(business)
} catch (error) {
console.error('GET /api/businesses/[id] error:', error)
return NextResponse.json({ error: 'Erreur serveur' }, { status: 500 })
}
}
// PATCH /api/businesses/[id]
export async function PATCH(
request: NextRequest,
context: { params: Promise<{ id: string }> }
): Promise<Response> {
try {
const { id } = await context.params
const body = await request.json()
const business = await prisma.business.update({
where: { id },
data: body,
include: { owner: true, offers: true },
})
return NextResponse.json(business)
} catch (error) {
console.error('PATCH /api/businesses/[id] error:', error)
return NextResponse.json({ error: 'Erreur lors de la mise à jour' }, { status: 500 })
}
}
// DELETE /api/businesses/[id]
export async function DELETE(
request: NextRequest,
context: { params: Promise<{ id: string }> }
): Promise<Response> {
try {
const { id } = await context.params
const headerUserId = request.headers.get('x-user-id')
// 1. Find business to check owner
const business = await prisma.business.findUnique({
where: { id },
select: { ownerId: true }
})
if (!business) {
return NextResponse.json({ error: 'Boutique non trouvée' }, { status: 404 })
}
// 2. Auth check (Owner or Admin)
const user = headerUserId ? await prisma.user.findUnique({ where: { id: headerUserId } }) : null
const isAdmin = user?.role === 'ADMIN'
const isOwner = business.ownerId === headerUserId
if (!isOwner && !isAdmin) {
return NextResponse.json({ error: 'Non autorisé' }, { status: 403 })
}
// 3. Delete business
await prisma.business.delete({ where: { id } })
// 4. Update user role if they don't have other businesses
if (headerUserId && !isAdmin) {
const otherBusinesses = await prisma.business.findFirst({
where: { ownerId: headerUserId }
})
if (!otherBusinesses) {
await prisma.user.update({
where: { id: headerUserId },
data: { role: 'VISITOR' }
})
}
}
return NextResponse.json({ success: true })
} catch (error) {
console.error('DELETE /api/businesses/[id] error:', error)
return NextResponse.json({ error: 'Erreur lors de la suppression' }, { status: 500 })
}
}