import { reconcileSumUpCheckouts } from '@/lib/sumup'

/**
 * Backstop de reconciliación para SumUp (que ya no ofrece webhooks): revisa los
 * checkouts SumUp pendientes y acredita los que estén PAID. Pensado para un cron
 * (systemd timer) que lo llame periódicamente. Protegido con CRON_SECRET.
 */
async function run(request: Request): Promise<Response> {
  const secret = process.env.CRON_SECRET
  if (!secret) return Response.json({ success: false, error: 'notConfigured' }, { status: 503 })

  const provided =
    request.headers.get('x-cron-secret') ||
    (request.headers.get('authorization') || '').replace(/^Bearer\s+/i, '')
  if (provided !== secret) return Response.json({ success: false, error: 'unauthorized' }, { status: 401 })

  const credited = await reconcileSumUpCheckouts({})
  return Response.json({ success: true, credited })
}

export async function POST(request: Request) {
  return run(request)
}

export async function GET(request: Request) {
  return run(request)
}
