import { NextRequest, NextResponse } from 'next/server'
import crypto from 'crypto'
import { runCleanup } from '@/lib/cleanup'

export const runtime = 'nodejs'
export const dynamic = 'force-dynamic'

function timingSafeEquals(a: string, b: string): boolean {
  const bufA = Buffer.from(a)
  const bufB = Buffer.from(b)
  if (bufA.length !== bufB.length) return false
  return crypto.timingSafeEqual(bufA, bufB)
}

/**
 * Deletes payloads for expired and soft-deleted transfers.
 *
 * Intended to be called on a schedule (cron, Vercel Cron, systemd timer):
 *   curl -X POST -H "Authorization: Bearer $CRON_SECRET" https://host/api/cron/cleanup
 *
 * Fails closed: without CRON_SECRET set, the endpoint refuses to run rather
 * than exposing bulk deletion unauthenticated.
 */
export async function POST(req: NextRequest) {
  const secret = process.env.CRON_SECRET

  if (!secret) {
    console.error('CRON_SECRET is not configured; refusing to run cleanup')
    return NextResponse.json({ error: 'Cleanup is not configured' }, { status: 503 })
  }

  const header = req.headers.get('authorization') || ''
  const provided = header.startsWith('Bearer ') ? header.slice(7) : ''

  if (!provided || !timingSafeEquals(provided, secret)) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
  }

  try {
    const report = await runCleanup()
    console.log('Cleanup report:', report)
    return NextResponse.json({ success: true, ...report })
  } catch (err) {
    console.error('Cleanup failed:', err)
    return NextResponse.json({ error: 'Cleanup failed' }, { status: 500 })
  }
}
