/**
 * Routes on trips created in HeavyHaul Agent are PURCHASED, never handed out
 * (Nash, 2026-10-01). Reading a permit finds its route token; that alone
 * gives nobody the route. Someone on the trip must take it — with a prepaid
 * credit or by paying — and the price follows how well the route is known:
 *
 *   the token is on 3 or more permits in our history (this one counts) → Express Route
 *   the token is on 2 or fewer                                          → Extended Route
 *
 * Prepaid credits cover Express Routes only. Permits pushed by Synchron
 * Permits are the exception — their route is included (`routeIncludedWithPermit`).
 * Pure rules; the counting and the payload gating live in
 * src/lib/data/route-offers.ts.
 */
import type { Permit, ServiceRequest, Trip } from '@/types/db'
import { routeIncludedWithPermit } from '@/lib/domain/permit-routes'
import type { RouteType } from '@/lib/domain/routing-products'

/** How many permits must carry a route token before its route counts as known. */
export const EXPRESS_MIN_TOKEN_USES = 3

export function routeTypeForTokenUses(uses: number): RouteType {
  return uses >= EXPRESS_MIN_TOKEN_USES ? 'express' : 'extended'
}

/** What the trip may do with one permit's route. */
export type RouteAccess =
  /** Comes with a Synchron permit — never sold. */
  | { kind: 'included' }
  /** Somebody on the trip took it (credit or payment). `ready` = the map exists. */
  | { kind: 'purchased'; ready: boolean }
  /** The permit is still being read; nothing to offer yet. */
  | { kind: 'reading' }
  /** For sale. */
  | { kind: 'offer'; route_type: RouteType; token_uses: number; uses_source?: TokenUsesSource }

/**
 * Where a usage count came from. MongoDB (through the agent backend) is the
 * source of truth; the other two are fallbacks for when it cannot answer.
 *   backend      — live lookup in MongoDB
 *   reader       — the count the backend returned when it read the permit
 *   workspace_db — permits in HeavyHaul Agent's own database (temporary fallback)
 */
export type TokenUsesSource = 'backend' | 'reader' | 'workspace_db' | 'none'

export interface RouteOffer {
  route_type: RouteType
  /** Permits that have used this route token, this one included. */
  token_uses: number
  uses_source?: TokenUsesSource
}

type RouteRequestLike = Pick<ServiceRequest, 'type' | 'state_code' | 'status' | 'permit_id'>

/**
 * The trip's live purchase of this permit's route, if any. New rows bind to
 * a permit. Only old/imported rows without that binding fall back to state.
 */
export function routePurchaseFor<T extends RouteRequestLike>(requests: T[], stateCode: string | null | undefined, permitId?: string | null): T | undefined {
  if (!stateCode) return undefined
  const live = requests.filter((r) => r.type === 'route_request' && r.status !== 'cancelled')
  if (permitId) {
    const exact = live.find((r) => r.permit_id === permitId)
    if (exact) return exact
  }
  return live.find((r) => !r.permit_id && r.state_code === stateCode)
}

export function hasRouteFiles(p: Pick<Permit, 'route_processing_status' | 'route_links' | 'route_gpx_url' | 'route_hummer_url'>): boolean {
  return p.route_processing_status === 'ready' && !!(p.route_links?.length || p.route_gpx_url || p.route_hummer_url)
}

export function routeAccess(params: {
  trip: Pick<Trip, 'permit_policy' | 'permit_source'>
  permit: Pick<Permit, 'id' | 'source_system' | 'state_code' | 'extraction_status' | 'route_processing_status' | 'route_links' | 'route_gpx_url' | 'route_hummer_url'>
  requests: RouteRequestLike[]
  /** Permits carrying this permit's route token (0 when it has none). */
  tokenUses: number
  usesSource?: TokenUsesSource
}): RouteAccess {
  const { trip, permit } = params
  if (routeIncludedWithPermit(trip, permit)) return { kind: 'included' }
  if (routePurchaseFor(params.requests, permit.state_code, permit.id)) return { kind: 'purchased', ready: hasRouteFiles(permit) }
  if (permit.extraction_status === 'pending' || !permit.state_code) return { kind: 'reading' }
  return {
    kind: 'offer', route_type: routeTypeForTokenUses(params.tokenUses), token_uses: params.tokenUses,
    ...(params.usesSource ? { uses_source: params.usesSource } : {}),
  }
}

/** May the route's files leave the server for this trip? */
export function routeFilesVisible(access: RouteAccess): boolean {
  return access.kind === 'included' || access.kind === 'purchased'
}

export const ROUTE_TYPE_LABELS: Record<RouteType, string> = { express: 'Express Route', extended: 'Extended Route' }

/** Shown once a route has been taken but its map is still being prepared. */
export const ROUTE_PURCHASED_PREPARING = 'Route purchased · being prepared'
