import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { connectDB } from "@/lib/db";
import { Client } from "@/models/Client";
import { Order } from "@/models/Order";
import { formatDateDE } from "@/lib/orderConstants";
import { getSessionClientId } from "@/lib/auth";
import { isAdminSession, hasPermission } from "@/lib/adminAuth";
import { corsHeaders, corsPreflight } from "@/lib/teamApiCors";

export async function OPTIONS(request: NextRequest) {
  return corsPreflight(request);
}

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

// Cross-Origin-Pendant zu /api/admin/clients/export — identische CSV-Logik.
export async function GET(request: NextRequest) {
  const headers = corsHeaders(request);
  const clientId = await getSessionClientId();
  if (!clientId || !(await isAdminSession()) || !(await hasPermission("clients_view"))) {
    return NextResponse.json({ error: "Nicht angemeldet." }, { status: 401, headers });
  }

  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");
  return new NextResponse(csv, { headers: { ...headers, "Content-Type": "text/csv; charset=utf-8", "Cache-Control": "private, max-age=0, no-store" } });
}
