import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/db";

export async function POST(req: NextRequest) {
  try {
    const body = await req.json();
    const { type, name, email, phone, subject, message, service } = body || {};

    if (!name || !phone || !message) {
      return NextResponse.json({ error: "Name, phone and message are required" }, { status: 400 });
    }

    // Basic rate limit by IP (in-memory)
    const ip = req.headers.get("x-forwarded-for") || "unknown";
    const key = `lead:${ip}`;
    const now = Date.now();
    const seen = (global as any).__leadRate;
    if (seen && seen[ip] && now - seen[ip] < 30000) {
      return NextResponse.json({ error: "Too many requests. Please wait a moment." }, { status: 429 });
    }
    (global as any).__leadRate = { ...(seen || {}), [ip]: now };

    const lead = await db.lead.create({
      data: {
        type: type || "CONTACT",
        name: String(name).slice(0, 120),
        email: email ? String(email).slice(0, 160) : null,
        phone: String(phone).slice(0, 40),
        subject: subject ? String(subject).slice(0, 200) : null,
        message: String(message).slice(0, 4000),
        service: service ? String(service).slice(0, 160) : null,
        status: "NEW",
      },
    });

    return NextResponse.json({ ok: true, id: lead.id });
  } catch (e) {
    console.error("Lead creation error:", e);
    return NextResponse.json({ error: "Internal server error" }, { status: 500 });
  }
}
