import { NextResponse } from "next/server";
import { contact } from "@/content/company";
import { allowedFieldsFor, pathIds, type PathId } from "@/content/paths";

/**
 * Enquiry endpoint.
 *
 * This validates and logs. It does not yet deliver, because delivery needs a
 * credential only Three Stars can provide.
 *
 * TO GO LIVE, pick one and fill in the marked block below.
 *
 *   Resend        npm i resend, set RESEND_API_KEY
 *   SMTP          npm i nodemailer, set SMTP_HOST, SMTP_USER, SMTP_PASS
 *
 * Until then the form still works for the visitor: it returns success and the
 * page offers a prefilled mailto as a guaranteed fallback route.
 */

export const runtime = "nodejs";

interface Payload {
  name: string;
  company: string;
  email: string;
  country: string;
  intent: string;
  division: string;
  quantity: string;
  message: string;
  /** Honeypot. Real people leave it empty. */
  website?: string;
}

const DIVISIONS = ["knitwear", "denim", "workwear", "yarn", "other"];

/** Anything longer than this is not a genuine answer to a one line question. */
const MAX_FIELD = 400;
const MAX_MESSAGE = 5000;

const clean = (value: unknown, limit = MAX_FIELD) =>
  String(value ?? "")
    .trim()
    .slice(0, limit);

export async function POST(request: Request) {
  let body: Partial<Payload>;

  try {
    body = (await request.json()) as Partial<Payload>;
  } catch {
    return NextResponse.json({ error: "Malformed request." }, { status: 400 });
  }

  // Silently accept and drop anything that filled the honeypot.
  if (body.website) {
    return NextResponse.json({ ok: true });
  }

  const errors: Record<string, string> = {};

  const name = clean(body.name);
  const email = clean(body.email);
  const message = clean(body.message, MAX_MESSAGE);
  const division = clean(body.division);
  const intent = clean(body.intent, 40);

  if (name.length < 2) errors.name = "Please tell us your name.";
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(email)) {
    errors.email = "Please give an email address we can reply to.";
  }
  if (message.length < 10) {
    errors.message = "A sentence or two about what you are making helps.";
  }
  if (division && !DIVISIONS.includes(division)) {
    errors.division = "Please choose one of the listed divisions.";
  }

  // "general" is the form with no path chosen. Anything else has to be a real
  // path id, so a hand crafted request cannot invent its own category.
  if (intent && intent !== "general" && !pathIds.includes(intent as PathId)) {
    errors.intent = "Unrecognised enquiry type.";
  }

  if (Object.keys(errors).length > 0) {
    return NextResponse.json({ errors }, { status: 422 });
  }

  // Path specific answers are copied across by whitelist, taken from the same
  // definition the form renders from. Whatever else is in the body is dropped
  // rather than logged, so this endpoint cannot be used to push arbitrary
  // content into the message that lands in their inbox.
  const details: Record<string, string> = {};
  const record = body as Record<string, unknown>;

  for (const field of allowedFieldsFor(intent)) {
    const value = clean(record[field]);
    if (value) details[field] = value;
  }

  const enquiry = {
    receivedAt: new Date().toISOString(),
    intent: intent || "general",
    name,
    email,
    company: clean(body.company),
    country: clean(body.country),
    message,
    ...(intent && intent !== "general"
      ? details
      : {
          division: division || "unspecified",
          quantity: clean(body.quantity),
        }),
  };

  // -------------------------------------------------------------------------
  // DELIVERY GOES HERE.
  //
  // Example with Resend:
  //
  //   const { Resend } = await import("resend");
  //   const resend = new Resend(process.env.RESEND_API_KEY);
  //   await resend.emails.send({
  //     from: "website@threestarspk.com",
  //     to: contact.email,
  //     replyTo: enquiry.email,
  //     subject: `Website enquiry: ${enquiry.company || enquiry.name}`,
  //     text: Object.entries(enquiry).map(([k, v]) => `${k}: ${v}`).join("\n"),
  //   });
  // -------------------------------------------------------------------------

  console.info("[inquiry] pending delivery to %s", contact.email, enquiry);

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