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

export async function GET(req: NextRequest) {
  const ctx = await getOrgContext();
  if (!ctx?.org || !canOrgModule(ctx.role, "finances")) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
  const sp = req.nextUrl.searchParams;
  const conf = sp.get("conf") ?? undefined;
  const { start, end } = rangeWindow(sp.get("range") ?? undefined, sp.get("from") ?? undefined, sp.get("to") ?? undefined);
  const createdIn = dateFilter(start, end);

  const payments = await db.payment.findMany({
    where: {
      registration: conf ? { conferenceId: conf, conference: { orgId: ctx.org.id } } : { conference: { orgId: ctx.org.id } },
      ...(createdIn ? { createdAt: createdIn } : {}),
    },
    orderBy: { createdAt: "desc" },
    include: { registration: { select: { name: true, email: true, regCode: true, conference: { select: { name: true } }, ticketType: { select: { name: true } } } } },
  });

  return csvResponse("transactions.csv", [
    ["Transaction ID", "Date", "Visitor", "Email", "Reg Code", "Conference", "Pass", "Gateway", "Amount", "Currency", "Status"],
    ...payments.map((p) => [
      p.txnId ?? p.id,
      p.createdAt.toISOString(),
      p.registration.name,
      p.registration.email,
      p.registration.regCode,
      p.registration.conference.name,
      p.registration.ticketType.name,
      p.gateway,
      (p.amount / 100).toFixed(2),
      p.currency,
      p.status,
    ]),
  ]);
}
