import { NextResponse } from "next/server";
import { desc } from "drizzle-orm";
import { requireAdmin } from "@/lib/auth/admin-guard";
import { db } from "@/lib/db/client";
import { users } from "@/lib/db/schema";
import { logAdminAction } from "@/lib/audit";

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

export async function GET() {
  const session = await requireAdmin();
  const adminId = (session.user as { id?: string }).id!;
  const rows = await db.select().from(users).orderBy(desc(users.createdAt));
  const header = [
    "id",
    "email",
    "name",
    "status",
    "role",
    "country",
    "institution",
    "professionalRole",
    "orcidUrl",
    "linkedinUrl",
    "createdAt",
    "approvedAt",
  ];
  const lines = [header.join(",")];
  for (const r of rows) {
    lines.push(
      [
        r.id,
        r.email,
        r.name,
        r.status,
        r.role,
        r.country,
        r.institution,
        r.professionalRole,
        r.orcidUrl ?? "",
        r.linkedinUrl ?? "",
        r.createdAt.toISOString(),
        r.approvedAt ? r.approvedAt.toISOString() : "",
      ]
        .map(csvEscape)
        .join(","),
    );
  }

  await logAdminAction({
    adminUserId: adminId,
    action: "members_export_csv",
    metadata: { count: rows.length },
  });

  const csv = lines.join("\n");
  return new NextResponse(csv, {
    headers: {
      "content-type": "text/csv; charset=utf-8",
      "content-disposition": `attachment; filename="orthoglobe-members-${new Date()
        .toISOString()
        .slice(0, 10)}.csv"`,
    },
  });
}
