import { NextResponse } from "next/server";
import { bookingSchema } from "@/lib/validation";
import { ApiRequestError, checkRateLimit, readJson } from "@/lib/api-security";
import { createBotBooking, getBotBookingDatePolicy } from "@/lib/bot-api";
import { currentUser } from "@/lib/auth";
import { getVerifiedPhone, normalizePhone } from "@/lib/sms-pin";
import { restaurantDateTimeInputToIso } from "@/lib/date-time";

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, durationMinutes, comment } = parsed.data;
    const policy = await getBotBookingDatePolicy();
    if (date < policy.min_date || date > policy.max_date || new Date(`${date}T${time}:00+03:00`).getTime() <= new Date(policy.server_time).getTime()) return NextResponse.json({ error: date > policy.max_date ? "Эта дата ещё недоступна" : "Эта дата уже прошла" }, { status: 400 });
    if (new Date(`${date}T${time}:00+03:00`).getTime() < new Date(policy.server_time).getTime() + 3600000) return NextResponse.json({ error: "Бронирование доступно минимум за час до начала." }, { status: 400 });
    const signedInUser = await currentUser();
    const signedInPhone = signedInUser ? await getVerifiedPhone(signedInUser.id) : null;
    const dateTime = restaurantDateTimeInputToIso(`${date}T${time}`);
    if (!dateTime) return NextResponse.json({ error: "Invalid booking datetime" }, { status: 400 });
    const result = await createBotBooking({
      customer_ref: signedInUser && signedInPhone === normalizePhone(phone)
        ? signedInUser.customerRef : undefined,
      name,
      phone,
      email: email || undefined,
      persons: guests,
      duration_minutes: durationMinutes,
      datetime: dateTime,
      comment: comment?.replace(/#/gu, "").slice(0, 500) || undefined
    });
    return NextResponse.json({
      id: result.rid,
      status: result.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 });
  }
}
