import { timingSafeEqual } from 'node:crypto'
import { NextRequest, NextResponse } from 'next/server'
import { z } from 'zod'
import { extractRateConfirmation } from '@/lib/adapters/flask'
import { resolveDocumentUrl } from '@/lib/data/document-urls'
import { isSynchronPermitUrl } from '@/lib/integrations/synchron-contract'
import { syncTripToHha } from '@/lib/integrations/hha-trip-sync'
import { S3_PREFIX, canonicalS3Url, deleteS3Object, uploadFileToS3 } from '@/lib/storage/s3'
import { createAdminClient } from '@/lib/supabase/admin'

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

const inputSchema = z.object({ trip_id: z.string().uuid(), document_id: z.string().uuid() })

function authorized(req: NextRequest): boolean {
  const expected = process.env.CRON_SECRET || ''
  const supplied = req.headers.get('authorization') || ''
  return expected.length >= 32 && Buffer.byteLength(supplied) === Buffer.byteLength(`Bearer ${expected}`)
    && timingSafeEqual(Buffer.from(supplied), Buffer.from(`Bearer ${expected}`))
}

/** Historical Synchron RateCons must use the same S3 uploader as Workspace uploads. */
export async function POST(req: NextRequest) {
  if (!authorized(req)) return NextResponse.json({ error: 'unauthorized' }, { status: 401 })
  const parsed = inputSchema.safeParse(await req.json().catch(() => ({})))
  if (!parsed.success) return NextResponse.json({ error: 'invalid_request' }, { status: 400 })
  const { trip_id: tripId, document_id: documentId } = parsed.data
  const admin = createAdminClient()
  const [tripResult, docResult] = await Promise.all([
    admin.from('trips').select('id,source_system').eq('id', tripId).single(),
    admin.from('documents').select('*').eq('id', documentId).eq('trip_id', tripId).single(),
  ])
  const trip = tripResult.data
  let document = docResult.data
  if (tripResult.error || docResult.error || trip?.source_system !== 'synchron' ||
      document?.source_system !== 'synchron' || document?.kind !== 'rate_confirmation') {
    return NextResponse.json({ error: 'synchron_ratecon_not_found' }, { status: 404 })
  }
  if (document.storage_provider !== 'external' && document.storage_provider !== 's3') {
    return NextResponse.json({ error: 'unsupported_ratecon_location' }, { status: 400 })
  }
  if (document.storage_provider === 'external' && !isSynchronPermitUrl(document.external_url || '')) {
    return NextResponse.json({ error: 'unapproved_ratecon_source' }, { status: 400 })
  }

  try {
    if (document.storage_provider === 's3' && document.text_extracted_at) {
      const sync = await syncTripToHha(tripId)
      if (!sync.ok) throw new Error('trip_sync_failed')
      return NextResponse.json({ ok: true, document_id: documentId, storage_provider: 's3', extracted: true, already_processed: true })
    }
    const url = await resolveDocumentUrl(document)
    if (!url) throw new Error('ratecon_file_unavailable')
    const response = await fetch(url, { redirect: 'error', signal: AbortSignal.timeout(30_000) })
    if (!response.ok || !response.body) throw new Error('ratecon_download_failed')
    const reader = response.body.getReader()
    const chunks: Uint8Array<ArrayBuffer>[] = []
    let size = 0
    try {
      while (true) {
        const { done, value } = await reader.read()
        if (done) break
        size += value.byteLength
        if (size > 25 * 1024 * 1024) { await reader.cancel(); throw new Error('ratecon_too_large') }
        chunks.push(new Uint8Array(value))
      }
    } finally { reader.releaseLock() }
    if (!size) throw new Error('empty_ratecon')
    const file = new Blob(chunks, { type: document.mime_type || 'application/octet-stream' })
    let canonicalUrl: string
    if (document.storage_provider === 'external') {
      const stored = await uploadFileToS3(file, document.file_name, S3_PREFIX.rateConfirmation)
      const updated = await admin.from('documents').update({
        storage_provider: 's3', storage_path: stored.key, external_url: stored.url,
        mime_type: stored.contentType, size_bytes: size,
      }).eq('id', documentId).eq('storage_provider', 'external').select('*').single()
      if (updated.error || !updated.data) {
        await deleteS3Object(stored.key).catch(() => undefined)
        throw new Error('ratecon_document_save_failed')
      }
      document = updated.data
      canonicalUrl = stored.url
    } else {
      canonicalUrl = canonicalS3Url(document.storage_path)
    }
    const extraction = await extractRateConfirmation(file, document.file_name, {
      tripId, documentId, sourceUrl: canonicalUrl,
    })
    if (!extraction.ok) throw new Error('ratecon_extraction_failed')
    const saved = await admin.from('documents').update({ text_extracted_at: new Date().toISOString() }).eq('id', documentId)
    if (saved.error) throw new Error('ratecon_extraction_marker_failed')
    const sync = await syncTripToHha(tripId)
    if (!sync.ok) throw new Error('trip_sync_failed')
    return NextResponse.json({ ok: true, document_id: documentId, storage_provider: 's3', extracted: true })
  } catch (error) {
    const code = error instanceof Error && /^[a-z_]+$/.test(error.message)
      ? error.message : 'ratecon_processing_failed'
    console.error('synchron_import_ratecon', { trip_id: tripId, document_id: documentId, error: code })
    return NextResponse.json({ ok: false, error: code }, { status: 503 })
  }
}
