import { submitToStrapi, outcomeStatus } from "@/lib/strapi/submit"
import { clean, isEmail, hasLength, isBot, isDate, isTime } from "@/lib/forms/validation"
import { notifyWedding } from "@/lib/forms/email"

const HONEYPOT = "company"

export async function POST(request: Request) {
  let body: Record<string, unknown>
  try {
    body = (await request.json()) as Record<string, unknown>
  } catch {
    return Response.json({ ok: false, message: "Invalid JSON body." }, { status: 400 })
  }

  if (isBot(body[HONEYPOT])) {
    return Response.json({ ok: true })
  }

  const fullName = clean(body.fullName)
  const email = clean(body.email)
  const mobile = clean(body.mobile)
  const eventType = clean(body.eventType)
  const eventBudget = clean(body.eventBudget)
  const eventDateRaw = clean(body.eventDate)
  let eventTimeRaw = clean(body.eventTime)
  if (eventTimeRaw && eventTimeRaw.length === 5) {
    eventTimeRaw = `${eventTimeRaw}:00.000`
  }
  const requirements = clean(body.requirements)

  const errors: Record<string, string> = {}
  if (!hasLength(fullName, 1, 120)) errors.fullName = "Full name is required."
  if (!isEmail(email)) errors.email = "A valid email is required."
  const originalEventTimeRaw = clean(body.eventTime)
  if (eventDateRaw && !isDate(eventDateRaw)) errors.eventDate = "Invalid date."
  if (originalEventTimeRaw && !isTime(originalEventTimeRaw)) errors.eventTime = "Invalid time."
  if (Object.keys(errors).length > 0) {
    return Response.json({ ok: false, message: "Please fix the highlighted fields.", errors }, { status: 400 })
  }

  // Notify the site owner by email (best-effort, never blocks the submission).
  await notifyWedding({
    fullName,
    email,
    mobile,
    eventType,
    eventBudget,
    eventDate: eventDateRaw || null,
    eventTime: eventTimeRaw || null,
    requirements,
  })

  const result = await submitToStrapi("wedding-inquiries", {
    fullName,
    email,
    mobile,
    eventType,
    eventBudget,
    eventDate: eventDateRaw || null,
    eventTime: eventTimeRaw || null,
    requirements,
  })

  if (result.ok) return Response.json({ ok: true })
  return Response.json({ ok: false, message: result.message }, { status: outcomeStatus(result.reason) })
}
