import { NextRequest, NextResponse } from 'next/server'
import { createAdminClient } from '@/lib/supabase/admin'
import { syncTripToHha } from '@/lib/integrations/hha-trip-sync'

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

function authorized(req: NextRequest) {
  const expected = process.env.CRON_SECRET
  return Boolean(expected && req.headers.get('authorization') === `Bearer ${expected}`)
}

/** Reconcile one trip, or all trips, into GPT. Safe to repeat. */
export async function POST(req: NextRequest) {
  if (!authorized(req)) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })

  const input = (await req.json().catch(() => ({}))) as { trip_id?: string; skip_ref_codes?: string[] }
  const admin = createAdminClient()
  let query = admin.from('trips').select('id, ref_code').order('created_at', { ascending: true })
  if (input.trip_id) query = query.eq('id', input.trip_id)
  const { data: trips, error } = await query
  if (error) return NextResponse.json({ error: error.message }, { status: 500 })

  const skipped = new Set(input.skip_ref_codes ?? [])
  const candidates = (trips ?? []).filter((trip) => !skipped.has(trip.ref_code))
  const results: Array<{ trip_id: string; ok: boolean; error?: string }> = []
  for (let offset = 0; offset < candidates.length; offset += 5) {
    const batch = candidates.slice(offset, offset + 5)
    results.push(
      ...(await Promise.all(
        batch.map(async (trip) => {
          const result = await syncTripToHha(trip.id)
          return { trip_id: trip.id, ok: result.ok, error: result.error }
        }),
      )),
    )
  }

  return NextResponse.json({
    ok: results.every((result) => result.ok),
    total: results.length,
    synced: results.filter((result) => result.ok).length,
    failed: results.filter((result) => !result.ok),
  })
}
