import type { Permit, ServiceRequest, Trip } from '@/types/db'

export type PermitRouteFields = Pick<Permit, 'id' | 'trip_id' | 'state_code' |
  'route_processing_status' | 'route_links' | 'route_gpx_url' | 'route_hummer_url'>

/** Present automatic, permit-scoped delivery without creating a paid request. */
export function permitRouteRequest(p: PermitRouteFields): ServiceRequest | undefined {
  if (p.route_processing_status !== 'ready' ||
      !(p.route_links?.length || p.route_gpx_url || p.route_hummer_url)) return undefined
  return {
    id: `permit-route:${p.id}`, trip_id: p.trip_id, state_code: p.state_code,
    type: 'route_request', status: 'fulfilled', route_type: null,
    route_links: p.route_links || [], route_gpx_url: p.route_gpx_url || null,
    route_hummer_url: p.route_hummer_url || null, requested_by: null,
    requester_label: 'Automatic permit processing', notes: null, notify: null,
    paid_with: null, replaces_permit_id: null, created_at: '', updated_at: '',
  }
}

/**
 * Does this permit's route come with the permit? Decision D5 (2026-09-29) and
 * Nash (2026-10-01): "If the order is pushed by Synchron Permits, the route
 * is included… they should not have the button to buy the route or use
 * credits." True when the permit itself came from Synchron (webhook or
 * import: `permits.source_system = 'synchron'`), when the trip's permits are
 * ordered from Synchron (`trips.permit_source = 'synchron'` — carrier wizard
 * Synchron path and every imported order), or when the broker's intake
 * policy requires Synchron. Only a manually uploaded permit on a non-Synchron
 * trip is a route the customer may buy.
 */
export function routeIncludedWithPermit(
  trip: Pick<Trip, 'permit_policy' | 'permit_source'>,
  permit: Pick<Permit, 'source_system'>,
): boolean {
  if (permit.source_system === 'synchron') return true
  if (trip.permit_source === 'synchron') return true
  if (trip.permit_policy === 'synchron_required') return true
  return false
}

/** What to say next to "Route included" while Synchron still owes the route. */
export function includedRouteStatusLabel(status: Permit['route_processing_status']): string | null {
  if (status === 'ready') return null
  if (status === 'unsupported') return 'Needs manual preparation by Synchron Permits'
  return 'Processing by Synchron Permits'
}

export function permitRouteLabel(status: Permit['route_processing_status']): string {
  if (status === 'unsupported') return 'Route needs manual preparation'
  if (status === 'needs_preparation') return 'Route token assigned · map preparation pending'
  if (status === 'failed') return 'Route processing pending retry'
  return 'Route processing · no credits deducted'
}
