import { NextResponse } from "next/server";
import { hasPermission } from "@/lib/adminAuth";
import { connectDB } from "@/lib/db";
import { Client } from "@/models/Client";
import { Order } from "@/models/Order";
import { formatDateDE } from "@/lib/orderConstants";

function csvEscape(value: string | number): string {
  const s = String(value);
  return /[",\n;]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
}

export async function GET() {
  if (!(await hasPermission("clients_view"))) return new NextResponse("Unauthorized", { status: 401 });

  await connectDB();
  const clients = await Client.find({ role: "client" }).sort({ name: 1 }).lean();
  const orderCounts = await Order.aggregate([
    { $match: { clientId: { $in: clients.map((c) => c._id) } } },
    { $group: { _id: "$clientId", count: { $sum: 1 } } },
  ]);
  const orderCountByClientId = new Map(orderCounts.map((o) => [String(o._id), o.count]));

  const lines: string[] = [];
  lines.push(["Name", "Spitzname", "E-Mail", "Telefon", "Unternehmen", "Anschrift", "Tags", "Verifiziert", "Registriert am", "Aufträge"].map(csvEscape).join(";"));
  for (const c of clients) {
    lines.push(
      [
        c.name,
        c.nickname || "",
        c.email,
        c.phone || "",
        c.company || "",
        (c.address || "").replace(/\n/g, ", "),
        (c.tags || []).join(", "),
        c.verified ? "ja" : "nein",
        formatDateDE(new Date(c.createdAt)),
        orderCountByClientId.get(String(c._id)) ?? 0,
      ]
        .map(csvEscape)
        .join(";")
    );
  }

  const csv = "﻿" + lines.join("\n"); // BOM für korrekte Umlaute in Excel
  return new NextResponse(csv, {
    headers: {
      "Content-Type": "text/csv; charset=utf-8",
      "Content-Disposition": `attachment; filename="kunden-${new Date().toISOString().slice(0, 10)}.csv"`,
      "Cache-Control": "private, max-age=0, no-store",
    },
  });
}
