import { getDb } from '@pintrush/db';
import { toCsv } from '@/lib/auth/csv';
import { isSameOriginRequest } from '@/lib/auth/same-origin';
import { getAdminContext } from '@/lib/auth/session';
import { siteUrl } from '@/lib/site';
import { adminAudit } from '../../../_lib/audit';
import { LEAD_STATUSES } from '../../../_lib/constants';

/**
 * CSV export of pilot leads (optionally one status), admin-only. Cells are escaped and guarded
 * against spreadsheet formula injection (lib/auth/csv); the download is audited because it carries
 * contact details.
 *
 * POST from the leads page's own form only (no GET): a link or window.open on another site would
 * otherwise carry the SameSite=Lax admin cookie, download every lead and write a false audit row.
 */
export async function POST(request: Request): Promise<Response> {
  const noStore = { 'Cache-Control': 'no-store' };
  if (!isSameOriginRequest(request.headers, [siteUrl.origin, new URL(request.url).origin])) {
    return new Response('Export leads from the Pilot leads page.', { status: 403, headers: noStore });
  }
  const ctx = await getAdminContext();
  if (!ctx) return new Response('Sign in as a PintRush admin to export leads.', { status: 401, headers: noStore });

  const form = await request.formData().catch(() => null);
  const field = form?.get('status');
  const raw = typeof field === 'string' ? field : null;
  const status = raw && (LEAD_STATUSES as readonly string[]).includes(raw) ? (raw as (typeof LEAD_STATUSES)[number]) : null;
  const db = getDb();
  const leads = await db.pilotLead.findMany({
    where: status ? { status } : {},
    orderBy: { createdAt: 'desc' },
    take: 10_000,
    select: {
      id: true,
      createdAt: true,
      status: true,
      venueName: true,
      address: true,
      contactName: true,
      email: true,
      phone: true,
      tvCount: true,
      busiestNights: true,
      currentEntertainment: true,
      message: true,
    },
  });
  await adminAudit(db, ctx.admin.id, 'admin.leads.exported', { status, rows: leads.length });

  const csv = toCsv(
    ['id', 'received_at', 'status', 'venue_name', 'address', 'contact_name', 'email', 'phone', 'tv_count', 'busiest_nights', 'current_entertainment', 'message'],
    leads.map((l) => [l.id, l.createdAt, l.status, l.venueName, l.address, l.contactName, l.email, l.phone, l.tvCount, l.busiestNights, l.currentEntertainment, l.message]),
  );
  const date = new Date().toISOString().slice(0, 10);
  return new Response(csv, {
    headers: {
      'Content-Type': 'text/csv; charset=utf-8',
      'Content-Disposition': `attachment; filename="pintrush-pilot-leads${status ? `-${status.toLowerCase()}` : ''}-${date}.csv"`,
      'Cache-Control': 'no-store, private',
      'X-Content-Type-Options': 'nosniff',
      'X-Robots-Tag': 'noindex',
    },
  });
}
