import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'

/**
 * Regression (Nash, 2026-10-01): the Create Trip wizard showed 0 in the load
 * dimension boxes. The reader turned a missing value into 0 (Number('') is 0),
 * so a rate con with no dimensions looked like one that said "0". A missing
 * dimension must come back as "no value".
 */
const respond = (ext_info: Record<string, unknown>) =>
  vi.fn(async () => new Response(JSON.stringify({ ext_info }), { status: 200, headers: { 'Content-Type': 'application/json' } }))

describe('extractRateConfirmation — load dimensions', () => {
  beforeEach(() => { vi.stubEnv('FLASK_API_BASE_URL', 'http://reader.test') })
  afterEach(() => { vi.unstubAllEnvs(); vi.unstubAllGlobals() })

  async function read(ext_info: Record<string, unknown>) {
    vi.stubGlobal('fetch', respond(ext_info))
    const { extractRateConfirmation } = await import('@/lib/adapters/flask')
    const r = await extractRateConfirmation(new Blob(['x']), 'rc.pdf')
    expect(r.ok).toBe(true)
    return r.data!
  }

  it('returns no value when the rate con states no dimensions', async () => {
    const d = await read({ pickup_address: 'Houston, TX', delivery_address: 'Denver, CO', commodity_details: {} })
    expect(d.length_in).toBeUndefined()
    expect(d.width_in).toBeUndefined()
    expect(d.height_in).toBeUndefined()
    expect(d.weight_lbs).toBeUndefined()
  })

  it('returns no value for empty strings, zeros and zero feet/inches objects', async () => {
    const d = await read({ commodity_details: { length: '', width: '0', height: { feet: 0, inches: 0 }, weight: 0 } })
    expect(d.length_in).toBeUndefined()
    expect(d.width_in).toBeUndefined()
    expect(d.height_in).toBeUndefined()
    expect(d.weight_lbs).toBeUndefined()
  })

  it('still converts real dimensions to inches and keeps the weight', async () => {
    const d = await read({ commodity_details: { length: "40'", width: '10 ft 6 in', height: { feet: 12, inches: 0 }, weight: '48,000 lbs' } })
    expect(d.length_in).toBe(480)
    expect(d.width_in).toBe(126)
    expect(d.height_in).toBe(144)
    expect(d.weight_lbs).toBe(48000)
  })
})

describe('extractPermit — route usage count from MongoDB', () => {
  beforeEach(() => { vi.stubEnv('FLASK_API_BASE_URL', 'http://reader.test') })
  afterEach(() => { vi.unstubAllEnvs(); vi.unstubAllGlobals() })

  async function readPermit(state: Record<string, unknown>) {
    vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({ states_info: [{ state_name: 'Texas', route_token: '4411', route_status: 'needs_preparation', ...state }] }), { status: 200, headers: { 'Content-Type': 'application/json' } })))
    const { extractPermit } = await import('@/lib/adapters/flask')
    const r = await extractPermit(new Blob(['x']), 'permit.pdf')
    expect(r.ok).toBe(true)
    return r.data!
  }

  it('carries the count when the backend sends it', async () => {
    expect((await readPermit({ route_usage_count: 6 })).route_usage_count).toBe(6)
    expect((await readPermit({ route_usage_count: '3' })).route_usage_count).toBe(3)
    expect((await readPermit({ route_usage_count: 0 })).route_usage_count).toBe(0)
  })
  it('is absent, never zero, when the backend does not send it', async () => {
    expect((await readPermit({})).route_usage_count).toBeUndefined()
    expect((await readPermit({ route_usage_count: 'many' })).route_usage_count).toBeUndefined()
    expect((await readPermit({ route_usage_count: -1 })).route_usage_count).toBeUndefined()
  })
})

describe('getRouteTokenUsage — live lookup', () => {
  beforeEach(() => { vi.stubEnv('FLASK_API_BASE_URL', 'http://reader.test') })
  afterEach(() => { vi.unstubAllEnvs(); vi.unstubAllGlobals() })

  it('posts state-scoped routes once each and returns whole-number counts only', async () => {
    const fetchMock = vi.fn(async () => new Response(JSON.stringify({ usage: { 'TX::4411': 9, 'CA::workspace:abc': '2', bad: 'x' } }), { status: 200, headers: { 'Content-Type': 'application/json' } }))
    vi.stubGlobal('fetch', fetchMock)
    const { getRouteTokenUsage } = await import('@/lib/adapters/flask')
    const r = await getRouteTokenUsage([
      { routeToken: '4411', stateCode: 'TX' },
      { routeToken: '4411', stateCode: 'TX' },
      { routeToken: 'workspace:abc', stateCode: 'CA' },
      { routeToken: 'bad', stateCode: 'TX' },
      { routeToken: 'missing', stateCode: 'TX' },
    ])
    expect(r).toEqual({ ok: true, data: { 'TX::4411': 9, 'CA::workspace:abc': 2 } })
    const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit]
    expect(url).toBe('http://reader.test/api/workspace/route-token-usage')
    expect(JSON.parse(String(init.body))).toEqual({ routes: [
      { route_token: '4411', state_code: 'TX' },
      { route_token: 'workspace:abc', state_code: 'CA' },
      { route_token: 'bad', state_code: 'TX' },
      { route_token: 'missing', state_code: 'TX' },
    ] })
  })
  it('reports failure when the endpoint is not there yet, so callers fall back', async () => {
    vi.stubGlobal('fetch', vi.fn(async () => new Response('not found', { status: 404 })))
    const { getRouteTokenUsage } = await import('@/lib/adapters/flask')
    expect((await getRouteTokenUsage([{ routeToken: '4411', stateCode: 'TX' }])).ok).toBe(false)
  })
})
