import { beforeEach, describe, expect, it, vi } from 'vitest'
import { createFakeSupabase } from './stubs/fake-supabase'

const db = createFakeSupabase()
const audit = vi.hoisted(() => ({ logTripEvent: vi.fn(async () => {}) }))
const hha = vi.hoisted(() => ({ syncTripToHha: vi.fn(async () => ({ ok: true })) }))
vi.mock('@/lib/supabase/admin', () => ({ createAdminClient: () => db }))
vi.mock('@/lib/audit', () => audit)
vi.mock('@/lib/integrations/hha-trip-sync', () => hha)

const { reconcileTripCarrier } = await import('@/lib/data/trip-carrier-validation')

const tripId = '322e7814-5b8a-4aa7-846f-9ea669c0c001'
const alpha = '322e7814-5b8a-4aa7-846f-9ea669c0c002'
const beta = '322e7814-5b8a-4aa7-846f-9ea669c0c003'
const extraction = (name: string, dot: string) => ({ raw: { order_info: { carrier_info: { name, dot } } } })

function seedBase(carrierCompanyId: string | null = null) {
  db.seed('trips', [{ id: tripId, carrier_company_id: carrierCompanyId, carrier_name: carrierCompanyId === beta ? 'Beta Logistics' : null, carrier_validation: null }])
  db.seed('companies', [
    { id: alpha, company_type: 'carrier', display_name: 'Alpha Freight LLC', legal_name: 'Alpha Freight LLC', dot_number: '123', dot_normalized: '123', merged_into: null },
    { id: beta, company_type: 'carrier', display_name: 'Beta Logistics', legal_name: 'Beta Logistics', dot_number: '456', dot_normalized: '456', merged_into: null },
  ])
}

beforeEach(() => {
  db.reset()
  audit.logTripEvent.mockClear()
  hha.syncTripToHha.mockClear()
})

describe('permit-backed trip carrier validation', () => {
  it('attaches the one known carrier supported by permit readings', async () => {
    seedBase()
    db.seed('permits', [{ trip_id: tripId, extraction: extraction('Alpha Freight', '123') }])

    await expect(reconcileTripCarrier({ tripId, sync: false })).resolves.toMatchObject({
      status: 'validated', changed: true, locked: false, carrierCompanyId: alpha,
    })
    expect(db.table('trips')[0]).toMatchObject({ carrier_company_id: alpha, carrier_name: 'Alpha Freight LLC', carrier_validation: 'validated' })
    expect(audit.logTripEvent).toHaveBeenCalledWith(expect.objectContaining({ action: 'carrier_validated_assigned', sync: false }))
  })

  it('corrects a different automatic assignment before the first paid purchase', async () => {
    seedBase(beta)
    db.seed('permits', [{ trip_id: tripId, extraction: extraction('Alpha Freight', '123') }])

    await expect(reconcileTripCarrier({ tripId, sync: false })).resolves.toMatchObject({ status: 'validated', changed: true, carrierCompanyId: alpha })
    expect(db.table('trips')[0].carrier_company_id).toBe(alpha)
    expect(audit.logTripEvent).toHaveBeenCalledWith(expect.objectContaining({ action: 'carrier_validated_replaced' }))
  })

  it('never replaces a carrier after a paid route purchase and records the review state once', async () => {
    seedBase(beta)
    db.seed('permits', [{ trip_id: tripId, extraction: extraction('Alpha Freight', '123') }])
    db.seed('purchases', [{ hha_trip_id: tripId, purchase_status: 'paid' }])

    await expect(reconcileTripCarrier({ tripId, sync: false })).resolves.toMatchObject({ status: 'needs_confirmation', changed: false, locked: true, carrierCompanyId: beta })
    expect(db.table('trips')[0]).toMatchObject({ carrier_company_id: beta, carrier_validation: 'needs_confirmation' })
    expect(audit.logTripEvent).toHaveBeenCalledWith(expect.objectContaining({ action: 'carrier_validation_locked_after_paid_purchase' }))

    await reconcileTripCarrier({ tripId, sync: false })
    expect(audit.logTripEvent).toHaveBeenCalledTimes(1)
  })

  it('never replaces a locked carrier even when it is the unique plurality result', async () => {
    seedBase(beta)
    db.seed('permits', [
      ...Array.from({ length: 5 }, () => ({ trip_id: tripId, extraction: extraction('Alpha Freight', '123') })),
      ...Array.from({ length: 4 }, () => ({ trip_id: tripId, extraction: extraction('Beta Logistics', '456') })),
      ...Array.from({ length: 2 }, () => ({ trip_id: tripId, extraction: extraction('Gamma Haul', '789') })),
    ])
    db.seed('purchases', [{ hha_trip_id: tripId, purchase_status: 'paid' }])

    await expect(reconcileTripCarrier({ tripId, sync: false })).resolves.toMatchObject({
      status: 'needs_confirmation', changed: false, locked: true, carrierCompanyId: beta,
    })
    expect(db.table('trips')[0].carrier_company_id).toBe(beta)
  })

  it('keeps the trip unassigned when a clear reading has no unique platform carrier', async () => {
    seedBase()
    db.seed('permits', [{ trip_id: tripId, extraction: extraction('Unknown Carrier', '999') }])

    await expect(reconcileTripCarrier({ tripId, sync: false })).resolves.toMatchObject({ status: 'needs_confirmation', changed: false, carrierCompanyId: null })
    expect(db.table('trips')[0].carrier_company_id).toBeNull()
  })
})
