import { submitToStrapi, outcomeStatus } from "@/lib/strapi/submit"
import { clean, isEmail, isBot } from "@/lib/forms/validation"
import { notifyNewsletter } 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 email = clean(body.email)
  if (!isEmail(email)) {
    return Response.json(
      { ok: false, message: "Please enter a valid email address.", errors: { email: "Invalid email." } },
      { status: 400 },
    )
  }

  // Notify the site owner by email (best-effort, never blocks the submission).
  await notifyNewsletter(email)

  const result = await submitToStrapi("newsletter-subscribers", { email })

  // Already subscribed → treat as success for the user, with a hint.
  if (!result.ok && result.reason === "duplicate") {
    return Response.json({ ok: true, alreadySubscribed: true })
  }

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