import { NextResponse } from "next/server";

/**
 * Lead intake.
 *
 * This validates and acknowledges the submission but does not yet forward it
 * anywhere — wire the marked section to your CRM, transactional email or
 * database before going live, or leads will be accepted and dropped.
 */

type LeadPayload = {
  property?: string;
  roof?: string;
  bill?: string;
  timeframe?: string;
  name?: string;
  email?: string;
  postcode?: string;
};

const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

export async function POST(request: Request) {
  let payload: LeadPayload;

  try {
    payload = await request.json();
  } catch {
    return NextResponse.json(
      { ok: false, error: "Malformed request body." },
      { status: 400 },
    );
  }

  const name = payload.name?.trim() ?? "";
  const email = payload.email?.trim() ?? "";

  if (name.length < 2) {
    return NextResponse.json(
      { ok: false, error: "Please give us a name we can use." },
      { status: 422 },
    );
  }

  if (!EMAIL_RE.test(email)) {
    return NextResponse.json(
      { ok: false, error: "That email address doesn't look right." },
      { status: 422 },
    );
  }

  const reference = `CS-${Date.now().toString(36).toUpperCase().slice(-6)}`;

  // ---- Wire your destination here (CRM / email / database) ----
  console.log("[lead]", reference, {
    name,
    email,
    postcode: payload.postcode ?? "",
    property: payload.property ?? "",
    roof: payload.roof ?? "",
    bill: payload.bill ?? "",
    timeframe: payload.timeframe ?? "",
  });
  // -------------------------------------------------------------

  return NextResponse.json({ ok: true, reference });
}
