import { requireAdminApi } from "@/lib/admin-api";
import { prisma } from "@/lib/prisma";
import { NextResponse } from "next/server";

export async function GET() {
  const deny = await requireAdminApi();
  if (deny) return deny;

  const rows = await prisma.reservation.findMany({
    orderBy: { createdAt: "desc" },
    take: 200,
  });
  return NextResponse.json(rows);
}

export async function PATCH(req: Request) {
  const deny = await requireAdminApi();
  if (deny) return deny;

  try {
    const body = await req.json();
    const id = String(body.id ?? "");
    const status = String(body.status ?? "");
    if (!id || !["pending", "confirmed", "cancelled"].includes(status)) {
      return NextResponse.json({ error: "Invalid" }, { status: 400 });
    }

    const row = await prisma.reservation.update({
      where: { id },
      data: { status },
    });
    return NextResponse.json(row);
  } catch {
    return NextResponse.json({ error: "Not found" }, { status: 404 });
  }
}
