import { NextRequest, NextResponse } from "next/server"
import prisma from "@/lib/prisma"
import { getOrgId } from "@/lib/session"

/**
 * GET /api/onboarding — role-aware setup progress
 * Returns different checklist for charities vs fundraisers
 * orgType=null means user hasn't chosen yet
 */
export async function GET() {
  const orgId = await getOrgId(null)
  if (!orgId || !prisma) return NextResponse.json({ steps: [], needsRole: true })

  const [org, eventCount, qrCount, pledgeCount] = await Promise.all([
    prisma.organization.findUnique({
      where: { id: orgId },
      select: {
        name: true, orgType: true, bankSortCode: true, bankAccountNo: true,
        whatsappConnected: true,
      },
    }),
    prisma.event.count({ where: { organizationId: orgId } }),
    prisma.qrSource.count({ where: { event: { organizationId: orgId } } }),
    prisma.pledge.count({ where: { organizationId: orgId } }),
  ])

  // Check if event has external URL (for fundraiser check)
  const hasExternalEvent = await prisma.event.count({
    where: { organizationId: orgId, paymentMode: "external", externalUrl: { not: null } },
  })

  const orgType = org?.orgType || null // null = hasn't picked yet
  const hasBank = !!(org?.bankSortCode && org?.bankAccountNo)
  const hasEvent = eventCount > 0
  const hasQr = qrCount > 0
  const hasPledge = pledgeCount > 0
  const hasWhatsApp = org?.whatsappConnected || false

  // Build steps based on org type
  type Step = { id: string; label: string; desc: string; done: boolean; href: string; action?: string }
  const steps: Step[] = []

  if (!orgType || orgType === "charity") {
    // CHARITY flow — needs bank details
    steps.push(
      { id: "bank", label: "Add bank details", desc: "So donors know where to send money", done: hasBank, href: "/dashboard/settings" },
      { id: "whatsapp", label: "Connect WhatsApp", desc: "Auto-send receipts & reminders to donors", done: hasWhatsApp, href: "/dashboard/settings", action: "whatsapp" },
      { id: "event", label: "Create a campaign", desc: "Name your fundraiser and set a goal", done: hasEvent, href: "/dashboard/events" },
      { id: "share", label: "Share your pledge link", desc: "Send via WhatsApp, social media, email, or print a QR", done: hasQr, href: "/dashboard/events" },
    )
  } else {
    // FUNDRAISER flow — needs external URL, no bank
    steps.push(
      { id: "event", label: "Add your fundraising page", desc: "Paste your LaunchGood, Enthuse or JustGiving link", done: hasExternalEvent > 0, href: "/dashboard/events" },
      { id: "whatsapp", label: "Connect WhatsApp", desc: "Auto-remind donors to complete their pledge", done: hasWhatsApp, href: "/dashboard/settings", action: "whatsapp" },
      { id: "share", label: "Share your pledge link", desc: "WhatsApp, social media, email, or QR code", done: hasQr, href: "/dashboard/events" },
      { id: "pledge", label: "Get your first pledge", desc: "Share with your network to start collecting", done: hasPledge, href: "/dashboard/pledges" },
    )
  }

  const completed = steps.filter(s => s.done).length
  const allDone = completed === steps.length

  return NextResponse.json({
    steps,
    completed,
    total: steps.length,
    allDone,
    orgType,
    needsRole: !orgType || orgType === "charity", // charity is default — show role picker if not explicitly set
    orgName: org?.name,
  })
}

/**
 * POST /api/onboarding — set org type (charity vs fundraiser)
 */
export async function POST(request: NextRequest) {
  const orgId = await getOrgId(null)
  if (!orgId || !prisma) return NextResponse.json({ error: "Not found" }, { status: 404 })

  const body = await request.json()
  const orgType = body.orgType

  if (!["charity", "fundraiser"].includes(orgType)) {
    return NextResponse.json({ error: "Invalid orgType" }, { status: 400 })
  }

  await prisma.organization.update({
    where: { id: orgId },
    data: { orgType },
  })

  return NextResponse.json({ ok: true, orgType })
}
