import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";

type LeadPayload = {
  company?: string;
  phone?: string;
  email?: string;
  message?: string;
};

export async function POST(request: Request) {
  try {
    const body = (await request.json()) as LeadPayload;

    const company = body.company?.trim();
    const phone = body.phone?.trim();
    const email = body.email?.trim().toLowerCase();
    const message = body.message?.trim() || "";

    if (!company || !phone || !email) {
      return NextResponse.json(
        { error: "Компания, телефон и email обязательны" },
        { status: 400 }
      );
    }

    const lead = await prisma.lead.create({
      data: {
        company,
        phone,
        email,
        message,
        source: "website",
      },
    });

    return NextResponse.json({ success: true, leadId: lead.id }, { status: 201 });
  } catch (error) {
    console.error("POST /api/leads error:", error);
    return NextResponse.json(
      { error: "Не удалось сохранить заявку" },
      { status: 500 }
    );
  }
}