import { timingSafeEqual } from 'node:crypto'
import { NextRequest, NextResponse } from 'next/server'
import { z } from 'zod'
import { evaluateParticipantRulesById } from '@/lib/data/auto-participants'

export const runtime = 'nodejs'
export const maxDuration = 120

const schema = z.object({
  trip_id: z.string().uuid(),
  participant_ids: z.array(z.string().uuid()).min(1).max(200),
  trigger: z.enum(['synchron_import', 'participation']).optional(),
})

/**
 * Run the Auto-Participant resolver for rows another process wrote (Task
 * 5.4, decision D9): the Synchron import scripts write a new order's people
 * who already have accounts as active participants, then call this once per
 * trip. Bearer CRON_SECRET, like the reconciliation job.
 */
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 parsed = schema.safeParse(await req.json().catch(() => ({})))
  if (!parsed.success) return NextResponse.json({ error: 'trip_id and participant_ids are required.' }, { status: 400 })
  const results = []
  for (const participantId of parsed.data.participant_ids) {
    const r = await evaluateParticipantRulesById({ tripId: parsed.data.trip_id, participantId, trigger: parsed.data.trigger ?? 'synchron_import', session: null })
    results.push({ participant_id: participantId, outcome: r?.outcome ?? 'failed', added: r?.added ?? [], rules: r?.rules ?? [] })
  }
  return NextResponse.json({ ok: true, results })
}
