import { NextResponse } from "next/server";
import { normalise, validate, type InquiryInput } from "@/lib/inquiry";

/**
 * POST /api/inquiry — business inquiry delivery.
 *
 * Delivery channels (first configured one wins; see .env.example):
 *  1. Resend email API  — RESEND_API_KEY + INQUIRY_TO_EMAIL + INQUIRY_FROM_EMAIL
 *  2. Generic webhook   — INQUIRY_WEBHOOK_URL (+ optional INQUIRY_WEBHOOK_SECRET),
 *                          e.g. a CRM, Zapier/Make, Slack workflow or form service.
 * With neither configured the endpoint answers 503 "not_configured" and the
 * form tells the visitor plainly that nothing was sent (no fake success).
 */

const WINDOW_MS = 60_000;
const MAX_PER_WINDOW = 5;
const hits = new Map<string, number[]>();

function rateLimited(ip: string) {
  const now = Date.now();
  const list = (hits.get(ip) ?? []).filter((t) => now - t < WINDOW_MS);
  list.push(now);
  hits.set(ip, list);
  if (hits.size > 5000) hits.clear();
  return list.length > MAX_PER_WINDOW;
}

const escape = (s: string) =>
  s.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c] as string);

function summary(v: InquiryInput) {
  return [
    `Name: ${v.name}`,
    `Company / Organization: ${v.company}`,
    `Email: ${v.email}`,
    `Phone: ${v.phone || "—"}`,
    `Subject: ${v.subject}`,
    `Language: ${v.locale || "en"}`,
    "",
    v.message,
  ].join("\n");
}

async function sendWithResend(v: InquiryInput) {
  const res = await fetch("https://api.resend.com/emails", {
    method: "POST",
    headers: { Authorization: `Bearer ${process.env.RESEND_API_KEY}`, "Content-Type": "application/json" },
    body: JSON.stringify({
      from: process.env.INQUIRY_FROM_EMAIL,
      to: process.env.INQUIRY_TO_EMAIL!.split(",").map((s) => s.trim()),
      reply_to: v.email,
      subject: `[Website inquiry] ${v.subject} — ${v.name}`,
      text: summary(v),
      html: `<pre style="font-family:system-ui,sans-serif;white-space:pre-wrap">${escape(summary(v))}</pre>`,
    }),
    signal: AbortSignal.timeout(10_000),
  });
  if (!res.ok) throw new Error(`Resend responded ${res.status}`);
}

async function sendWithWebhook(v: InquiryInput) {
  const headers: Record<string, string> = { "Content-Type": "application/json" };
  if (process.env.INQUIRY_WEBHOOK_SECRET) headers.Authorization = `Bearer ${process.env.INQUIRY_WEBHOOK_SECRET}`;
  const res = await fetch(process.env.INQUIRY_WEBHOOK_URL!, {
    method: "POST",
    headers,
    body: JSON.stringify({
      source: "arsy-pusaka-website",
      receivedAt: new Date().toISOString(),
      name: v.name,
      company: v.company,
      email: v.email,
      phone: v.phone,
      subject: v.subject,
      message: v.message,
      locale: v.locale,
    }),
    signal: AbortSignal.timeout(10_000),
  });
  if (!res.ok) throw new Error(`Webhook responded ${res.status}`);
}

export async function POST(request: Request) {
  const ip = (request.headers.get("x-forwarded-for") ?? "").split(",")[0].trim() || "local";
  if (rateLimited(ip)) return NextResponse.json({ ok: false, code: "rate_limited" }, { status: 429 });

  let body: Record<string, unknown>;
  try {
    body = await request.json();
  } catch {
    return NextResponse.json({ ok: false, code: "bad_request" }, { status: 400 });
  }

  const input = normalise(body);
  // Honeypot filled → silently accept so bots learn nothing; nothing is delivered.
  if (input.website) return NextResponse.json({ ok: true });

  const errors = validate(input);
  if (Object.keys(errors).length) return NextResponse.json({ ok: false, code: "invalid", errors }, { status: 422 });

  const hasResend = !!(process.env.RESEND_API_KEY && process.env.INQUIRY_TO_EMAIL && process.env.INQUIRY_FROM_EMAIL);
  const hasWebhook = !!process.env.INQUIRY_WEBHOOK_URL;
  if (!hasResend && !hasWebhook) {
    return NextResponse.json({ ok: false, code: "not_configured" }, { status: 503 });
  }

  try {
    if (hasResend) await sendWithResend(input);
    else await sendWithWebhook(input);
    return NextResponse.json({ ok: true });
  } catch (err) {
    console.error("[inquiry] delivery failed:", err instanceof Error ? err.message : err);
    return NextResponse.json({ ok: false, code: "delivery_failed" }, { status: 502 });
  }
}
