import { NextRequest, NextResponse } from "next/server";
import { bookingSchema } from "@/lib/validation";
import { sendNotification } from "@/lib/notifications";
import { rateLimit } from "@/lib/rate-limit";
import { getServices } from "@/lib/content";

export async function POST(request: NextRequest) {
  const ip = request.headers.get("x-forwarded-for")?.split(",")[0] || "local";
  if (!rateLimit(`inquiry:${ip}`, 5, 15 * 60_000)) return NextResponse.json({ error: "Please wait before trying again." }, { status: 429 });

  const parsed = bookingSchema.safeParse(await request.json().catch(() => null));
  if (!parsed.success) return NextResponse.json({ error: "Please check the form details and try again." }, { status: 400 });

  const inquiry = parsed.data;
  const service = (await getServices()).find(item => item.id === inquiry.serviceId);
  if (!service) return NextResponse.json({ error: "Please select an available service." }, { status: 400 });

  try {
    const result = await sendNotification({
      type: "booking",
      payload: {
        name: inquiry.name,
        email: inquiry.email,
        phone: inquiry.phone,
        service: service.name,
        preferredDate: inquiry.date,
        preferredTime: inquiry.time,
        inspirationLink: inquiry.inspirationUrl || "Not provided",
        message: inquiry.notes || "Not provided",
      },
    });
    if (!result.sent) return NextResponse.json({ error: "Email is not configured yet. Please contact Ella directly at hello@nailsbyella.com." }, { status: 503 });
    return NextResponse.json({ ok: true });
  } catch {
    return NextResponse.json({ error: "The email could not be sent. Please contact Ella directly at hello@nailsbyella.com." }, { status: 502 });
  }
}
