import { NextResponse } from "next/server"; import { query, queryOne } from "@/lib/db"; import { loadTranslationsFor, replaceTranslations } from "@/lib/db/translations"; import { authErrorResponse, requireRole } from "@/lib/auth/session"; import { isSameOrigin } from "@/lib/origin"; import type { Dish } from "@/lib/types"; interface DishRow { id: string; name: string; price: string; allergens: string[]; additives: string[]; } export async function PATCH( request: Request, { params }: { params: Promise<{ id: string }> } ) { if (!isSameOrigin(request)) { return NextResponse.json({ error: "Nicht erlaubt." }, { status: 403 }); } try { await requireRole(["staff", "admin"]); const { id } = await params; const body = (await request.json()) as { name: string; price: number; allergens: string[]; additives: string[]; translations?: Record; }; const row = await queryOne( `update dishes set name = $1, price = $2, allergens = $3, additives = $4 where id = $5 returning id, name, price, allergens, additives`, [body.name, body.price, body.allergens, body.additives, id] ); if (!row) return NextResponse.json({ error: "not_found" }, { status: 404 }); if (body.translations) { await replaceTranslations("dish_translations", row.id, body.translations); } const translations = await loadTranslationsFor("dish_translations", [row.id]); const dish: Dish = { ...row, price: Number(row.price), translations: translations.get(row.id) ?? {}, }; return NextResponse.json(dish); } catch (err) { const res = authErrorResponse(err); if (res) return res; throw err; } } export async function DELETE( request: Request, { params }: { params: Promise<{ id: string }> } ) { if (!isSameOrigin(request)) { return NextResponse.json({ error: "Nicht erlaubt." }, { status: 403 }); } try { await requireRole(["staff", "admin"]); const { id } = await params; await query("delete from dishes where id = $1", [id]); return NextResponse.json({ ok: true }); } catch (err) { const res = authErrorResponse(err); if (res) return res; throw err; } }