import { NextRequest, NextResponse } from "next/server";
import { auth } from "../../../../auth";
import fs from "fs/promises";
import path from "path";

const BOOKINGS_PATH = path.join(process.cwd(), "content", "bookings.json");

export async function GET() {
  const raw = await fs.readFile(BOOKINGS_PATH, "utf-8").catch(() => '{"bookings":[]}');
  return NextResponse.json(JSON.parse(raw));
}

export async function POST(req: NextRequest) {
  const session = await auth();
  if (!session?.user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const { bookings } = await req.json();
  if (!Array.isArray(bookings)) {
    return NextResponse.json({ error: "Invalid data" }, { status: 400 });
  }

  await fs.writeFile(BOOKINGS_PATH, JSON.stringify({ bookings }, null, 2), "utf-8");
  return NextResponse.json({ ok: true });
}
