import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/db";
import { getOrgContext, canOrgModule } from "@/lib/org";
import { csvResponse } from "@/lib/csv";

export async function GET(req: NextRequest) {
  const ctx = await getOrgContext();
  if (!ctx?.org || !canOrgModule(ctx.role, "visitors")) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
  // Viewers can see the table but exports are a staff capability.
  if (ctx.role === "VIEWER") return NextResponse.json({ error: "Exports are not available to viewers." }, { status: 403 });
  const sp = req.nextUrl.searchParams;

  const rows = await db.registration.findMany({
    where: {
      conference: { orgId: ctx.org.id },
      ...(sp.get("conf") ? { conferenceId: sp.get("conf")! } : {}),
      ...(sp.get("status") ? { status: sp.get("status")! } : {}),
      ...(sp.get("type") ? { ticketType: { audience: sp.get("type")! } } : {}),
      ...(sp.get("checkin") === "in" ? { checkIns: { some: { type: "CONFERENCE" } } } : {}),
      ...(sp.get("checkin") === "out" ? { checkIns: { none: { type: "CONFERENCE" } } } : {}),
      ...(sp.get("q")
        ? { OR: [{ name: { contains: sp.get("q")! } }, { email: { contains: sp.get("q")! } }, { organization: { contains: sp.get("q")! } }] }
        : {}),
    },
    orderBy: { createdAt: "desc" },
    include: {
      conference: { select: { name: true } },
      ticketType: { select: { name: true, audience: true } },
      checkIns: { where: { type: "CONFERENCE" }, select: { id: true } },
    },
  });

  return csvResponse("visitors.csv", [
    ["Reg Code", "Name", "Email", "Phone", "Organization", "Designation", "City", "Type", "Pass", "Conference", "Registered On", "Amount", "Payment Status", "Checked In"],
    ...rows.map((r) => [
      r.regCode, r.name, r.email, r.phone ?? "", r.organization ?? "", r.designation ?? "", r.city ?? "",
      r.ticketType.audience, r.ticketType.name, r.conference.name, r.createdAt.toISOString(),
      (r.amount / 100).toFixed(2), r.status, r.checkIns.length > 0 ? "YES" : "NO",
    ]),
  ]);
}
