import { prisma } from "@/lib/prisma";
import { NextResponse } from "next/server";

export async function POST(req: Request) {
  try {
    const body = await req.json();
    const name = String(body.name ?? "").trim();
    const email = String(body.email ?? "").trim();
    const phone = String(body.phone ?? "").trim();
    const partySize = Number(body.partySize);
    const date = body.date ? new Date(body.date) : null;
    const time = String(body.time ?? "").trim();
    const message =
      body.message != null && String(body.message).trim()
        ? String(body.message).trim()
        : null;

    if (
      !name ||
      !email ||
      !phone ||
      !Number.isFinite(partySize) ||
      partySize < 1 ||
      !date ||
      Number.isNaN(date.getTime()) ||
      !time
    ) {
      return NextResponse.json({ error: "Invalid payload" }, { status: 400 });
    }

    await prisma.reservation.create({
      data: {
        name,
        email,
        phone,
        partySize: Math.min(50, Math.floor(partySize)),
        date,
        time,
        message,
        status: "pending",
      },
    });

    return NextResponse.json({ ok: true });
  } catch {
    return NextResponse.json({ error: "Server error" }, { status: 500 });
  }
}
