import { submitToStrapi, outcomeStatus } from "@/lib/strapi/submit"
import { clean, isEmail, hasLength, isBot } from "@/lib/forms/validation"
import { notifyHospitality } 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 enquiryType = clean(body.enquiryType)
  const message = clean(body.message)

  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."
  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 notifyHospitality({ fullName, email, enquiryType, message })

  const result = await submitToStrapi("hospitality-inquiries", {
    fullName,
    email,
    enquiryType,
    message,
  })

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