import { NextResponse } from "next/server";
import { bookingSchema } from "@/lib/validation";
import { ApiRequestError, checkRateLimit, readJson } from "@/lib/api-security";
import { createBotBooking } from "@/lib/bot-api";

export async function POST(request: Request) {
  try {
    checkRateLimit(request, "booking", 10);
    const parsed = bookingSchema.safeParse(await readJson<unknown>(request, 16 * 1024));
    if (!parsed.success || parsed.data.website) {
      return NextResponse.json({ error: parsed.success ? "Invalid booking request" : parsed.error.issues[0]?.message || "Invalid booking request" }, { status: 400 });
    }
    const { name, phone, email, date, time, guests, comment } = parsed.data;
    const result = await createBotBooking({
      name,
      phone,
      email: email || undefined,
      persons: guests,
      datetime: `${date}T${time}`,
      comment: comment?.replace(/#/gu, "").slice(0, 500) || undefined
    });
    return NextResponse.json({
      id: result.rid,
      status: "new",
      message: result.message,
      bookingUrl: result.booking_url
    }, { headers: { "Cache-Control": "no-store" } });
  } catch (error) {
    const botError = error as Error & { status?: number };
    const isClientError = botError.status && botError.status >= 400 && botError.status < 500;
    const status = error instanceof ApiRequestError ? error.status : isClientError ? botError.status : 502;
    const message = error instanceof ApiRequestError || isClientError
      ? botError.message
      : "Сервис бронирования временно недоступен. Позвоните нам или попробуйте ещё раз позже.";
    return NextResponse.json({ error: message || "Invalid booking request" }, { status });
  }
}
