import { NextRequest, NextResponse } from "next/server"; import { insertDemoRequest } from "@/lib/db/demo-requests"; const INBOX_URL = process.env.LEAD_INBOX_URL; const INBOX_KEY = process.env.LEAD_INBOX_KEY; type Lead = { email: string; name: string; company: string; phone: string; industry: string; message: string; }; // Forward to the central lead-inbox (infra ADR 012). Returns true on success. // Server-side only — the key never reaches the browser. async function forwardToInbox(lead: Lead, source: string): Promise { if (!INBOX_URL || !INBOX_KEY) return false; try { const res = await fetch(`${INBOX_URL.replace(/\/+$/, "")}/v1/leads`, { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${INBOX_KEY}`, }, body: JSON.stringify({ ...lead, source }), signal: AbortSignal.timeout(5000), }); return res.ok; } catch { return false; } } export async function POST(req: NextRequest) { try { const body = await req.json(); const str = (v: unknown) => (typeof v === "string" ? v.trim() : ""); const { email, firstName, lastName, company, industry, phone, message } = body; // name = first + last; fall back to a legacy single `name` field. const name = [str(firstName), str(lastName)].filter(Boolean).join(" ") || str(body.name); // Optional lead source (e.g. waitlist vs demo); defaults to the demo label // so existing callers keep their behaviour. const source = str(body.source) || "HiveGrid Demo-Anfrage"; if (!email || typeof email !== "string" || !email.includes("@")) { return NextResponse.json( { error: "Gültige E-Mail-Adresse erforderlich." }, { status: 400 } ); } if (!name) { return NextResponse.json( { error: "Name ist erforderlich." }, { status: 400 } ); } const lead: Lead = { email: email.trim().toLowerCase(), name, company: str(company), phone: str(phone), industry: str(industry), message: str(message), }; // Central inbox is the source of truth; the local SQLite is the fallback // so a lead is never lost if the inbox is unreachable (ADR 012). When // LEAD_INBOX_URL/KEY are unset this is exactly the old local-only behavior. const forwarded = await forwardToInbox(lead, source); if (!forwarded) { // SQLite fallback stores only email/name/company/message, so fold the // extra fields into the message text — nothing is lost without a migration. const extra = [ lead.phone && `Telefon: ${lead.phone}`, lead.industry && `Branche: ${lead.industry}`, ].filter(Boolean); const message = [lead.message, ...extra].filter(Boolean).join("\n"); insertDemoRequest({ email: lead.email, name: lead.name, company: lead.company, message }); } return NextResponse.json({ success: true }); } catch (err) { console.error("Demo request error:", err); return NextResponse.json( { error: "Interner Fehler. Bitte versuchen Sie es später erneut." }, { status: 500 } ); } }