import { timingSafeEqual } from 'node:crypto'
import { NextRequest, NextResponse } from 'next/server'
import { createAdminClient } from '@/lib/supabase/admin'
import { publicOrigin } from '@/lib/app-url'
import { billingForPurchase, loadPurchase, reconcilePurchase } from '@/lib/data/purchases'
import type { Purchase } from '@/types/db'

export const runtime = 'nodejs'
export const maxDuration = 300

const STALE_AFTER_MS = 2 * 60_000
const BATCH = 50

/**
 * Reconciliation job (task §6.5, §26 "callback delayed"): every purchase
 * still `pending_payment` and untouched for 2+ minutes is checked against
 * Synchron through the verified confirmation path. Bearer CRON_SECRET.
 */
export async function POST(req: NextRequest) {
  const expected = process.env.CRON_SECRET || ''
  const supplied = req.headers.get('authorization') || ''
  const valid = expected.length >= 32 && Buffer.byteLength(supplied) === Buffer.byteLength(`Bearer ${expected}`)
    && timingSafeEqual(Buffer.from(supplied), Buffer.from(`Bearer ${expected}`))
  if (!valid) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })

  const cutoff = new Date(Date.now() - STALE_AFTER_MS).toISOString()
  const { data, error } = await createAdminClient()
    .from('purchases')
    .select('id')
    .eq('purchase_status', 'pending_payment')
    .lt('updated_at', cutoff)
    .order('updated_at', { ascending: true })
    .limit(BATCH)
  if (error) return NextResponse.json({ error: 'Purchase lookup failed' }, { status: 503 })

  const appOrigin = publicOrigin(req)
  const counts = { checked: 0, changed: 0, unchanged: 0, failed: 0 }
  for (const row of (data ?? []) as Pick<Purchase, 'id'>[]) {
    const bundle = await loadPurchase(row.id)
    if (!bundle) continue
    counts.checked += 1
    const result = await reconcilePurchase({ bundle, billing: await billingForPurchase(bundle), appOrigin, actorLabel: 'reconciliation job' })
    if (!result.ok) counts.failed += 1
    else if (result.changed) counts.changed += 1
    else counts.unchanged += 1
  }
  return NextResponse.json({ ok: true, ...counts })
}

export const GET = POST
