import { NextRequest, NextResponse } from "next/server"; import { prisma } from "@/lib/db"; export async function PATCH(req: NextRequest, { params }: { params: Promise<{ id: string }> }) { try { const { id } = await params; const body = await req.json() as Record; const oldLead = await prisma.lead.findUnique({ where: { id } }); if (!oldLead) return NextResponse.json({ error: "Not found" }, { status: 404 }); const allowedFields = [ "status", "priority", "notes", "tags", "country", "headcount", "industry", "contactedAt", "companyName", "contactName", "contactTitle", "email", "phone", "linkedinUrl", "domain", ]; const data: Record = {}; for (const field of allowedFields) { if (field in body) data[field] = body[field]; } const updated = await prisma.lead.update({ where: { id }, data }); // Track status change events if (body.status && body.status !== oldLead.status) { await prisma.leadEvent.create({ data: { leadId: id, event: `Status geƤndert zu "${body.status}"`, }, }); // Auto-set contactedAt when marking as contacted if (body.status === "contacted" && !oldLead.contactedAt) { await prisma.lead.update({ where: { id }, data: { contactedAt: new Date() } }); } } return NextResponse.json(updated); } catch (err) { console.error("PATCH /api/leads/[id] error:", err); return NextResponse.json({ error: "Update failed" }, { status: 500 }); } } export async function DELETE(_req: NextRequest, { params }: { params: Promise<{ id: string }> }) { try { const { id } = await params; await prisma.lead.delete({ where: { id } }); return NextResponse.json({ deleted: true }); } catch (err) { console.error("DELETE /api/leads/[id] error:", err); return NextResponse.json({ error: "Delete failed" }, { status: 500 }); } } export async function GET(_req: NextRequest, { params }: { params: Promise<{ id: string }> }) { try { const { id } = await params; const lead = await prisma.lead.findUnique({ where: { id }, include: { events: { orderBy: { at: "asc" } } }, }); if (!lead) return NextResponse.json({ error: "Not found" }, { status: 404 }); return NextResponse.json(lead); } catch (err) { return NextResponse.json({ error: "Fetch failed" }, { status: 500 }); } }