import 'server-only'

import { logTripEvent } from '@/lib/audit'
import { carrierFromReading, normalizeCarrierName, validateTripCarrier, type CarrierEvidence } from '@/lib/domain/carrier-validation'
import { syncTripToHha } from '@/lib/integrations/hha-trip-sync'
import { createAdminClient } from '@/lib/supabase/admin'

type Admin = ReturnType<typeof createAdminClient>
type CompanyRow = {
  id: string
  display_name: string | null
  legal_name: string | null
  dba_name?: string | null
  dot_number: string | null
  dot_normalized?: string | null
  mc_number: string | null
  company_type: string
  merged_into: string | null
}
type TripRow = {
  id: string
  carrier_company_id: string | null
  carrier_name: string | null
  carrier_validation: 'validated' | 'needs_confirmation' | 'unverified' | null
}

const paidStatuses = ['paid', 'refund_pending', 'partially_refunded', 'refunded']

function companyEvidence(company: CompanyRow | null): CarrierEvidence | null {
  if (!company) return null
  return {
    name: company.display_name || company.legal_name || company.dba_name || null,
    usdot: String(company.dot_normalized || company.dot_number || '').replace(/\D/g, '') || null,
    mc: String(company.mc_number || '').replace(/\D/g, '') || null,
  }
}

function companyName(company: CompanyRow): string {
  return company.display_name || company.legal_name || company.dba_name || 'Carrier'
}

async function loadCurrentCarrier(admin: Admin, companyId: string | null): Promise<CompanyRow | null> {
  if (!companyId) return null
  const result = await admin.from('companies')
    .select('id,display_name,legal_name,dba_name,dot_number,dot_normalized,mc_number,company_type,merged_into')
    .eq('id', companyId).eq('company_type', 'carrier').is('merged_into', null).maybeSingle()
  if (result.error) throw new Error('carrier_lookup_failed')
  return result.data as CompanyRow | null
}

/**
 * Resolve only an existing Workspace carrier. A permit reading is useful
 * evidence, but must never silently create a new carrier company.
 */
async function resolveExistingCarrier(admin: Admin, evidence: CarrierEvidence): Promise<CompanyRow | null> {
  if (evidence.usdot) {
    const byDot = await admin.from('companies')
      .select('id,display_name,legal_name,dba_name,dot_number,dot_normalized,mc_number,company_type,merged_into')
      .eq('company_type', 'carrier').is('merged_into', null).eq('dot_normalized', evidence.usdot)
    if (byDot.error) throw new Error('carrier_lookup_failed')
    const matches = (byDot.data || []) as CompanyRow[]
    if (matches.length === 1) return matches[0]
    // Two platform companies with one USDOT need an administrator's choice.
    if (matches.length > 1) return null
  }
  if (!evidence.name) return null
  const all = await admin.from('companies')
    .select('id,display_name,legal_name,dba_name,dot_number,dot_normalized,mc_number,company_type,merged_into')
    .eq('company_type', 'carrier').is('merged_into', null)
  if (all.error) throw new Error('carrier_lookup_failed')
  const key = normalizeCarrierName(evidence.name)
  const matches = ((all.data || []) as CompanyRow[]).filter((company) =>
    [company.display_name, company.legal_name, company.dba_name]
      .filter((name): name is string => !!name)
      .some((name) => normalizeCarrierName(name) === key),
  )
  return matches.length === 1 ? matches[0] : null
}

/**
 * Reconcile the trip carrier from all stored permit readings. This is an
 * internal, evidence-based write: the manual carrier picker remains locked
 * after its first assignment. Before a paid route purchase, a clear permit
 * majority may correct an automatic assignment; after payment it is retained
 * and the discrepancy is recorded for review.
 */
export async function reconcileTripCarrier(params: { tripId: string; sync?: boolean }) {
  const admin = createAdminClient()
  const { data: tripData, error: tripError } = await admin.from('trips')
    .select('id,carrier_company_id,carrier_name,carrier_validation').eq('id', params.tripId).maybeSingle()
  if (tripError || !tripData) throw new Error('trip_not_found')
  const trip = tripData as TripRow
  // Keep these immutable across the update below. Real PostgREST returns a
  // detached object, while the test adapter deliberately mutates its seed.
  const previousCarrierId = trip.carrier_company_id
  const previousValidation = trip.carrier_validation ?? null
  const permits = await admin.from('permits').select('extraction').eq('trip_id', trip.id)
  if (permits.error) throw new Error('permit_readings_unavailable')
  const currentCompany = await loadCurrentCarrier(admin, trip.carrier_company_id)
  const current = companyEvidence(currentCompany) || (trip.carrier_name ? { name: trip.carrier_name, usdot: null, mc: null } : null)
  const validation = validateTripCarrier({
    permits: (permits.data || []).map((permit) => carrierFromReading((permit as { extraction?: unknown }).extraction)),
    current,
  })

  let status: TripRow['carrier_validation'] = validation.status
  let nextCarrier = currentCompany
  let changed = false
  let locked = false

  if (validation.status === 'validated') {
    const candidate = await resolveExistingCarrier(admin, validation.carrier)
    if (!candidate) {
      // The reading has a clear majority but cannot be matched safely to one
      // platform carrier. Keep the current choice and show a review state.
      status = 'needs_confirmation'
    } else if (!trip.carrier_company_id) {
      nextCarrier = candidate
      changed = true
    } else if (previousCarrierId !== candidate.id) {
      const paid = await admin.from('purchases').select('id').eq('hha_trip_id', trip.id)
        .in('purchase_status', paidStatuses).limit(1)
      if (paid.error) throw new Error('purchase_lookup_failed')
      if ((paid.data || []).length > 0) {
        status = 'needs_confirmation'
        locked = true
      } else {
        nextCarrier = candidate
        changed = true
      }
    }
  }

  // A new trip with no carrier evidence has nothing to persist or mirror. If
  // a previous reading did have a result, a later re-read may still reset it
  // to unverified, so retain that transition.
  const shouldPersist = changed || locked || status !== previousValidation && !(status === 'unverified' && previousValidation === null)
  if (!shouldPersist) {
    return { status, changed, locked, carrierCompanyId: nextCarrier?.id || previousCarrierId || null }
  }

  const patch: Record<string, unknown> = {
    carrier_validation: status,
    carrier_validated_at: new Date().toISOString(),
  }
  if (changed && nextCarrier) {
    patch.carrier_company_id = nextCarrier.id
    patch.carrier_name = companyName(nextCarrier)
  }
  const saved = await admin.from('trips').update(patch).eq('id', trip.id)
  if (saved.error) throw new Error('carrier_validation_save_failed')

  if (changed && nextCarrier) {
    await logTripEvent({
      tripId: trip.id, actorLabel: 'HeavyHaul Agent', sync: false,
      action: previousCarrierId ? 'carrier_validated_replaced' : 'carrier_validated_assigned',
      detail: {
        previous_company_id: previousCarrierId,
        company_id: nextCarrier.id,
        name: companyName(nextCarrier),
        reason: 'permit_reading_majority',
      },
    })
  } else if (locked && previousValidation !== 'needs_confirmation') {
    await logTripEvent({
      tripId: trip.id, actorLabel: 'HeavyHaul Agent', sync: false,
      action: 'carrier_validation_locked_after_paid_purchase',
      detail: { company_id: previousCarrierId, reason: 'permit_reading_disagrees_with_paid_trip' },
    })
  }

  if (params.sync !== false && (changed || status !== previousValidation)) {
    const sync = await syncTripToHha(trip.id)
    if (!sync.ok) console.error('Carrier validation trip sync failed:', sync.error)
  }
  return { status, changed, locked, carrierCompanyId: nextCarrier?.id || previousCarrierId || null }
}
