import { NextRequest, NextResponse } from "next/server"
import prisma from "@/lib/prisma"
import { formatCrmExportCsv, type CrmExportRow } from "@/lib/exports"
import { resolveOrgId } from "@/lib/org"

interface ExportPledge {
  reference: string
  donorName: string | null
  donorEmail: string | null
  donorPhone: string | null
  amountPence: number
  rail: string
  status: string
  giftAid: boolean
  createdAt: Date
  paidAt: Date | null
  event: { name: string }
  qrSource: { label: string; volunteerName: string | null; tableName: string | null } | null
}

export async function GET(request: NextRequest) {
  try {
    if (!prisma) {
      return NextResponse.json({ error: "Database not configured" }, { status: 503 })
    }
    const orgId = await resolveOrgId(
      request.headers.get("x-org-id") || request.nextUrl.searchParams.get("orgId") || "demo"
    )
    if (!orgId) {
      return NextResponse.json({ error: "Organization not found" }, { status: 404 })
    }
    const eventId = request.nextUrl.searchParams.get("eventId")

    const pledges = await prisma.pledge.findMany({
      where: {
        organizationId: orgId,
        ...(eventId ? { eventId } : {}),
      },
      include: {
        event: { select: { name: true } },
        qrSource: { select: { label: true, volunteerName: true, tableName: true } },
      },
      orderBy: { createdAt: "desc" },
    }) as ExportPledge[]

    const rows: CrmExportRow[] = pledges.map((p: ExportPledge) => ({
      pledge_reference: p.reference,
      donor_name: p.donorName || "",
      donor_email: p.donorEmail || "",
      donor_phone: p.donorPhone || "",
      amount_gbp: (p.amountPence / 100).toFixed(2),
      payment_method: p.rail,
      status: p.status,
      event_name: p.event.name,
      source_label: p.qrSource?.label || "",
      volunteer_name: p.qrSource?.volunteerName || "",
      table_name: p.qrSource?.tableName || "",
      gift_aid: p.giftAid ? "Yes" : "No",
      pledged_at: p.createdAt.toISOString(),
      paid_at: p.paidAt?.toISOString() || "",
      days_to_collect: p.paidAt
        ? Math.ceil((p.paidAt.getTime() - p.createdAt.getTime()) / (1000 * 60 * 60 * 24)).toString()
        : "",
    }))

    const csv = formatCrmExportCsv(rows)

    return new NextResponse(csv, {
      headers: {
        "Content-Type": "text/csv",
        "Content-Disposition": `attachment; filename="crm-export-${new Date().toISOString().slice(0, 10)}.csv"`,
      },
    })
  } catch (error) {
    console.error("CRM export error:", error)
    return NextResponse.json({ error: "Internal error" }, { status: 500 })
  }
}
