import { submitToStrapi, outcomeStatus } from "@/lib/strapi/submit"
import { clean, isEmail, hasLength, isBot } from "@/lib/forms/validation"
import { notifyContact } 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 subject = clean(body.subject)
  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 (!hasLength(subject, 1, 200)) errors.subject = "Subject is required."
  if (!hasLength(message, 10, 5000)) errors.message = "Message must be at least 10 characters."
  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 notifyContact({ fullName, email, subject, message })

  const result = await submitToStrapi("contact-submissions", {
    fullName,
    email,
    subject,
    message,
  })

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