import { NextResponse } from "next/server";
import { db } from "@/lib/db";
import { getCurrentUser } from "@/lib/auth";
import { can, getMembership } from "@/lib/rbac";

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

/** Authenticated export: registrations as CSV (registrations.export — staff only, volunteers excluded). */
export async function GET(_req: Request, { params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  const membership = await getMembership(user.id, id);
  if (!can(membership, "registrations.export")) return NextResponse.json({ error: "Forbidden" }, { status: 403 });

  const regs = await db.registration.findMany({
    where: { conferenceId: id },
    orderBy: { createdAt: "asc" },
    include: { ticketType: true, checkIns: { where: { type: "CONFERENCE" } } },
  });

  const header = ["reg_code", "name", "email", "phone", "organization", "designation", "city", "ticket", "mode", "status", "amount_inr", "checked_in", "registered_at"];
  const rows = regs.map((r) => [
    r.regCode, r.name, r.email, r.phone, r.organization, r.designation, r.city,
    r.ticketType.name, r.mode, r.status, (r.amount / 100).toFixed(2),
    r.checkIns.length > 0 ? "yes" : "no", r.createdAt.toISOString(),
  ].map(csvCell).join(","));

  return new NextResponse([header.join(","), ...rows].join("\n"), {
    headers: {
      "Content-Type": "text/csv; charset=utf-8",
      "Content-Disposition": `attachment; filename="registrations-${id}.csv"`,
    },
  });
}
