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

/**
 * Mark overdue pledges.
 * Call via cron daily: GET /api/cron/overdue?key=SECRET
 *
 * A pledge is overdue if:
 * - status is "new" or "initiated"
 * - AND either:
 *   - dueDate is set and is more than 7 days ago
 *   - dueDate is null and createdAt is more than 14 days ago
 */
export async function GET(request: NextRequest) {
  const key = request.nextUrl.searchParams.get("key") || request.headers.get("x-cron-key")
  const expectedKey = process.env.CRON_SECRET || "pnpl-cron-2026"
  if (key !== expectedKey) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
  }

  if (!prisma) {
    return NextResponse.json({ error: "No DB" }, { status: 503 })
  }

  const now = new Date()
  const sevenDaysAgo = new Date(now.getTime() - 7 * 86400000)
  const fourteenDaysAgo = new Date(now.getTime() - 14 * 86400000)

  // Deferred pledges: 7 days past due date
  const overdueDeferred = await prisma.pledge.updateMany({
    where: {
      status: { in: ["new", "initiated"] },
      dueDate: { not: null, lt: sevenDaysAgo },
    },
    data: { status: "overdue" },
  })

  // Immediate pledges: 14 days since creation
  const overdueImmediate = await prisma.pledge.updateMany({
    where: {
      status: { in: ["new", "initiated"] },
      dueDate: null,
      createdAt: { lt: fourteenDaysAgo },
    },
    data: { status: "overdue" },
  })

  return NextResponse.json({
    markedOverdue: overdueDeferred.count + overdueImmediate.count,
    deferred: overdueDeferred.count,
    immediate: overdueImmediate.count,
    timestamp: now.toISOString(),
  })
}
