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

const mocks = vi.hoisted(() => ({
  getSessionUser: vi.fn(),
  createAdminClient: vi.fn(),
  uploadFileToS3: vi.fn(),
  deleteS3Object: vi.fn(),
  logTripEvent: vi.fn(),
  evaluateParticipantRules: vi.fn(),
  touchContactsForInvites: vi.fn(),
  redirect: vi.fn(),
  after: vi.fn(),
}))

vi.mock('next/navigation', () => ({ redirect: mocks.redirect }))
vi.mock('next/server', () => ({ after: mocks.after }))
vi.mock('@/lib/auth', () => ({ getSessionUser: mocks.getSessionUser }))
vi.mock('@/lib/supabase/admin', () => ({ createAdminClient: mocks.createAdminClient }))
vi.mock('@/lib/storage/s3', () => ({
  uploadFileToS3: mocks.uploadFileToS3,
  deleteS3Object: mocks.deleteS3Object,
  S3_PREFIX: { rateConfirmation: 'permits/rate_confirmations/', permit: 'permits/orderSteptwo/', tripSupporting: 'trips/' },
}))
vi.mock('@/lib/audit', () => ({ logTripEvent: mocks.logTripEvent }))
vi.mock('@/lib/data/auto-participants', () => ({ evaluateParticipantRules: mocks.evaluateParticipantRules }))
vi.mock('@/lib/data/contacts', () => ({ touchContactsForInvites: mocks.touchContactsForInvites }))
vi.mock('@/lib/data/permit-request-email', () => ({ sendInitialSynchronRequest: vi.fn() }))
vi.mock('@/lib/integrations/hha-trip-sync', () => ({ syncTripToHha: vi.fn() }))
vi.mock('@/lib/data/trip-background', () => ({ processNewTripInBackground: vi.fn() }))
vi.mock('@/lib/data/trip-numbers', () => ({ issueTripRefCode: vi.fn(async () => 'HH-512048337'), linkTripNumber: vi.fn(async () => undefined) }))

const { createCarrierTrip } = await import('@/app/trips/new/actions')

function form(fields: Record<string, string> = {}) {
  const data = new FormData()
  for (const [key, value] of Object.entries({
    origin: 'Tacoma, WA', destination: 'Macon, GA', commodity: 'Equipment', permit_path: 'upload', invites: '[]', ...fields,
  })) data.set(key, value)
  data.set('rate_confirmation', new File(['rate confirmation'], 'rate-con.pdf', { type: 'application/pdf' }))
  return data
}

function adminStub(unitError: { code: string } | null = null) {
  const calls: Array<{ table: string; operation: string; payload?: Record<string, unknown> }> = []
  const admin = {
    from(table: string) {
      return {
        insert(payload: Record<string, unknown>) {
          calls.push({ table, operation: 'insert', payload })
          const value = table === 'trip_units' ? { error: unitError } : { error: null }
          return {
            ...value,
            select() {
              return {
                single: async () => ({ data: table === 'trips'
                  ? { id: 'trip-uuid', ref_code: payload.ref_code }
                  : { id: table === 'documents' ? 'doc-uuid' : 'participant-uuid' }, error: null }),
                maybeSingle: async () => ({ data: { id: 'participant-uuid' }, error: null }),
              }
            },
          }
        },
        delete() {
          return { eq: async () => { calls.push({ table, operation: 'delete' }); return { error: null } } }
        },
      }
    },
  }
  mocks.createAdminClient.mockReturnValue(admin)
  return calls
}

beforeEach(() => {
  vi.resetAllMocks()
  mocks.getSessionUser.mockResolvedValue({ id: 'user-1', originId: 'user-1', role: 'dispatcher', email: 'dispatcher@example.test', name: 'Dispatcher', company: 'Carrier LLC' })
  mocks.uploadFileToS3.mockResolvedValue({ key: 'permits/rate_confirmations/file.pdf', url: 'https://example.test/file.pdf', contentType: 'application/pdf' })
  mocks.logTripEvent.mockResolvedValue(undefined)
  mocks.evaluateParticipantRules.mockResolvedValue(undefined)
  mocks.touchContactsForInvites.mockResolvedValue(undefined)
  mocks.redirect.mockImplementation(() => { throw new Error('redirected') })
})

describe('carrier trip creation', () => {
  it('stores confirmed overall dimensions and equipment while keeping the UUID internal', async () => {
    const calls = adminStub()
    await expect(createCarrierTrip(undefined, form({
      unit_number: 'T-455', load_weight_lbs: '42,000', overall_length_in: '936', overall_width_in: '144',
      overall_height_in: '168', overall_weight_lbs: '92,000', truck_vin: 'VIN455', truck_make: 'Peterbilt',
      truck_year: '2022', axle_count: '7', trailer_unit_number: 'TR-12', trailer_axle_count: '3',
    }))).rejects.toThrow('redirected')

    expect(calls.find((call) => call.table === 'trips' && call.operation === 'insert')?.payload)
      .toMatchObject({ unit_number: 'T-455', load_weight_lbs: 42000, overall_length_in: 936,
        overall_width_in: 144, overall_height_in: 168, overall_weight_lbs: 92000 })
    expect(calls.find((call) => call.table === 'trips' && call.operation === 'insert')?.payload?.ref_code)
      .toMatch(/^HH-\d{9}$/)
    expect(calls.find((call) => call.table === 'trip_units' && call.operation === 'insert')?.payload)
      .toMatchObject({ trip_id: 'trip-uuid', truck_unit_number: 'T-455', truck_vin: 'VIN455',
        truck_make: 'Peterbilt', truck_year: 2022, axle_count: 7, trailer_unit_number: 'TR-12', trailer_axle_count: 3 })
    expect(mocks.redirect).toHaveBeenCalledWith('/trips/trip-uuid')
  })

  it('does not invent an equipment row when all equipment fields are blank', async () => {
    const calls = adminStub()
    await expect(createCarrierTrip(undefined, form())).rejects.toThrow('redirected')
    expect(calls.some((call) => call.table === 'trip_units')).toBe(false)
  })

  it('rejects invalid axle counts before creating a trip', async () => {
    const calls = adminStub()
    const result = await createCarrierTrip(undefined, form({ axle_count: '31' }))
    expect(result?.error).toBeTruthy()
    expect(calls).toEqual([])
  })

  it('removes a just-created trip if its equipment snapshot cannot be saved', async () => {
    const calls = adminStub({ code: '23514' })
    const result = await createCarrierTrip(undefined, form({ unit_number: 'T-455' }))
    expect(result).toMatchObject({ error: expect.stringContaining('No trip was created') })
    expect(calls).toContainEqual({ table: 'trips', operation: 'delete' })
    expect(calls.some((call) => call.table === 'documents')).toBe(false)
  })
})
