import { NextRequest, NextResponse } from "next/server";
import { getGroupBookings, addGroupBooking, toggleGroupBookingNotification, deleteGroupBooking, setGroupBookingStatus, updateBookingNotes } from "@/lib/db";
import type { BookingStatus } from "@/lib/db";
import { sanitizeText } from "@/lib/validation";

export async function GET() {
  const bookings = getGroupBookings();
  return NextResponse.json(bookings, {
    headers: { "Cache-Control": "private, max-age=30" },
  });
}

export async function PUT(request: NextRequest) {
  try {
    const body = await request.json();
    if (body.action === "toggle-notify") {
      const { id, field, value } = body;
      if (!id || !field || typeof value !== "boolean") {
        return NextResponse.json({ error: "id, field, value are required" }, { status: 400 });
      }
      if (field !== "notified_confirm" && field !== "notified_reminder") {
        return NextResponse.json({ error: "Invalid field" }, { status: 400 });
      }
      toggleGroupBookingNotification(id, field, value);
      return NextResponse.json({ ok: true });
    }
    if (body.action === "set-status") {
      const { id, status, confirmation } = body;
      const valid: BookingStatus[] = ["new", "contacted", "confirmed", "declined"];
      if (!id || !valid.includes(status)) {
        return NextResponse.json({ error: "id and valid status are required" }, { status: 400 });
      }
      setGroupBookingStatus(id, status, confirmation);
      return NextResponse.json({ ok: true });
    }
    if (body.action === "set-notes") {
      const { id, notes } = body;
      if (!id) return NextResponse.json({ error: "id is required" }, { status: 400 });
      updateBookingNotes("group_bookings", id, sanitizeText(notes, 1000) ?? "");
      return NextResponse.json({ ok: true });
    }
    return NextResponse.json({ error: "Unknown action" }, { status: 400 });
  } catch (err) {
    console.error("[admin/group-bookings] error:", err);
    return NextResponse.json({ error: "Internal error" }, { status: 500 });
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { name, phone, instagram, telegram } = body;
    if (!name?.trim() || !phone?.trim()) {
      return NextResponse.json({ error: "name and phone are required" }, { status: 400 });
    }
    const id = addGroupBooking(name.trim(), phone.trim(), undefined, instagram?.trim() || undefined, telegram?.trim() || undefined);
    return NextResponse.json({ ok: true, id });
  } catch (err) {
    console.error("[admin/group-bookings] POST error:", err);
    return NextResponse.json({ error: "Internal error" }, { status: 500 });
  }
}

export async function DELETE(request: NextRequest) {
  const idStr = request.nextUrl.searchParams.get("id");
  if (!idStr) {
    return NextResponse.json({ error: "id parameter is required" }, { status: 400 });
  }
  const id = parseInt(idStr, 10);
  if (isNaN(id)) {
    return NextResponse.json({ error: "Invalid id" }, { status: 400 });
  }
  deleteGroupBooking(id);
  return NextResponse.json({ ok: true });
}
