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

const db = createFakeSupabase()
vi.mock('@/lib/supabase/admin', () => ({ createAdminClient: () => db }))

const { orderNumberFor, synchronOrderNumberForTrip } = await import('@/lib/data/trip-numbers')
const trip = { id: '378644e1-6503-4c5e-9149-41749dd6a006', ref_code: 'HH-512048337' }

beforeEach(() => {
  db.reset()
  vi.stubEnv('HHA_ENVIRONMENT', 'production')
  db.seed('trips', [{ ...trip, carrier_company_id: 'carrier-a' }])
})

describe('one trip, one carrier, one order number', () => {
  it('uses the trip number and returns the same binding on repeat', async () => {
    expect(await orderNumberFor(trip, 'carrier-a')).toBe('512048337')
    expect(await orderNumberFor(trip, 'carrier-a')).toBe('512048337')
    expect(db.table('trip_order_numbers')).toMatchObject([
      { order_number: '512048337', trip_id: trip.id, carrier_company_id: 'carrier-a' },
    ])
  })

  it('does not issue an order to a different carrier', async () => {
    await expect(orderNumberFor(trip, 'carrier-b')).rejects.toThrow('order_carrier_mismatch')
    expect(db.table('trip_order_numbers')).toHaveLength(0)
  })

  it('rejects a pre-existing second binding instead of selecting one', async () => {
    db.seed('trip_order_numbers', [
      { order_number: '512048337', trip_id: trip.id, carrier_company_id: 'carrier-a' },
      { order_number: '612048338', trip_id: trip.id, carrier_company_id: 'carrier-b' },
    ])
    await expect(orderNumberFor(trip, 'carrier-a')).rejects.toThrow('multiple orders')
  })

  it('does not mint a second number for an imported trip', async () => {
    await expect(orderNumberFor({ ...trip, ref_code: 'HH-38879104' }, 'carrier-a')).rejects.toThrow('order_not_purchasable')
  })

  it('requires the assigned carrier before an HHA trip sends work to Synchron', async () => {
    await expect(synchronOrderNumberForTrip({ ...trip, carrier_company_id: null }))
      .rejects.toThrow('carrier_required')
    expect(await synchronOrderNumberForTrip({ ...trip, carrier_company_id: 'carrier-a' })).toBe('512048337')
    expect(await synchronOrderNumberForTrip({ ...trip, ref_code: 'HH-38879104', carrier_company_id: 'carrier-a' })).toBeNull()
  })

  it('reuses the winning binding when two requests race', async () => {
    expect(await Promise.all([orderNumberFor(trip, 'carrier-a'), orderNumberFor(trip, 'carrier-a')]))
      .toEqual(['512048337', '512048337'])
    expect(db.table('trip_order_numbers')).toHaveLength(1)
  })
})
