import { NextRequest, NextResponse } from "next/server"; import { prisma } from "@/lib/db"; import { Prisma } from "@prisma/client"; import * as XLSX from "xlsx"; export async function GET(req: NextRequest) { try { const { searchParams } = new URL(req.url); const search = searchParams.get("search") || ""; const statuses = searchParams.getAll("status"); const sourceTabs = searchParams.getAll("sourceTab"); const priorities = searchParams.getAll("priority"); const hasEmail = searchParams.get("hasEmail"); const emailOnly = searchParams.get("emailOnly") === "true"; const format = searchParams.get("format") || "csv"; // "csv" | "xlsx" const where: Prisma.LeadWhereInput = {}; if (search) { where.OR = [ { domain: { contains: search } }, { companyName: { contains: search } }, { contactName: { contains: search } }, { email: { contains: search } }, ]; } if (statuses.length > 0) where.status = { in: statuses }; if (sourceTabs.length > 0) where.sourceTab = { in: sourceTabs }; if (priorities.length > 0) where.priority = { in: priorities }; if (hasEmail === "yes" || emailOnly) where.email = { not: null }; else if (hasEmail === "no") where.email = null; const leads = await prisma.lead.findMany({ where, orderBy: { capturedAt: "desc" }, take: 10000, }); const rows = leads.map(l => ({ "Unternehmen": l.companyName || "", "Domain": l.domain || "", "Kontaktname": l.contactName || "", "Position": l.contactTitle || "", "E-Mail": l.email || "", "Telefon": l.phone || "", "Adresse": l.address || "", "LinkedIn": l.linkedinUrl || "", "Branche": l.industry || "", "Suchbegriff": l.sourceTerm || "", "Tags": l.tags ? (JSON.parse(l.tags) as string[]).join(", ") : "", "Erfasst am": new Date(l.capturedAt).toLocaleDateString("de-DE", { day: "2-digit", month: "2-digit", year: "numeric" }), })); const filename = `onyva-leads-vault-${new Date().toISOString().split("T")[0]}`; if (format === "xlsx") { const ws = XLSX.utils.json_to_sheet(rows); // Column widths (one per column) ws["!cols"] = [ { wch: 30 }, // Unternehmen { wch: 28 }, // Domain { wch: 24 }, // Kontaktname { wch: 24 }, // Position { wch: 34 }, // E-Mail { wch: 18 }, // Telefon { wch: 36 }, // Adresse { wch: 36 }, // LinkedIn { wch: 22 }, // Branche { wch: 30 }, // Suchbegriff { wch: 28 }, // Tags { wch: 14 }, // Erfasst am ]; // Freeze header row ws["!freeze"] = { xSplit: 0, ySplit: 1 }; // Autofilter across all columns const colCount = Object.keys(rows[0] ?? {}).length || 17; const lastCol = String.fromCharCode(64 + colCount); ws["!autofilter"] = { ref: `A1:${lastCol}1` }; const wb = XLSX.utils.book_new(); XLSX.utils.book_append_sheet(wb, ws, "LeadVault"); const arr = XLSX.write(wb, { type: "array", bookType: "xlsx" }) as number[]; return new NextResponse(new Uint8Array(arr).buffer, { headers: { "Content-Type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Content-Disposition": `attachment; filename="${filename}.xlsx"`, }, }); } // CSV — UTF-8 BOM so Excel opens it correctly const colKeys = Object.keys(rows[0] ?? {}); const escape = (v: string) => v.includes(",") || v.includes('"') || v.includes("\n") || v.includes("\r") ? `"${v.replace(/"/g, '""')}"` : v; const csv = "\uFEFF" + [ colKeys.map(escape).join(","), ...rows.map(r => colKeys.map(h => escape(String(r[h as keyof typeof r] ?? ""))).join(",")), ].join("\r\n"); return new NextResponse(csv, { headers: { "Content-Type": "text/csv; charset=utf-8", "Content-Disposition": `attachment; filename="${filename}.csv"`, }, }); } catch (err) { console.error("GET /api/leads/export error:", err); return NextResponse.json({ error: "Export failed" }, { status: 500 }); } }