import { beforeEach, describe, expect, it, vi } from 'vitest'
import { chatPermitForState } from '@/lib/domain/chat-permit-selection'
const mocks = vi.hoisted(() => ({ admin: vi.fn(), calls: [] as unknown[][], result: { data: null, error: null } as { data: null | { id: string; state_code: string }; error: unknown } }))
vi.mock('@/lib/supabase/admin', () => ({ createAdminClient: mocks.admin }))
import { resolveChatPermit } from '@/lib/data/chat-permit-selection'
beforeEach(() => {
  mocks.calls = []; mocks.result = { data: null, error: null }
  const query = { select: vi.fn().mockReturnThis(),
    eq: vi.fn(function (this: unknown, ...args: unknown[]) { mocks.calls.push(['eq', ...args]); return this }),
    order: vi.fn(function (this: unknown, ...args: unknown[]) { mocks.calls.push(['order', ...args]); return this }),
    limit: vi.fn().mockReturnThis(), maybeSingle: vi.fn(async () => mocks.result),
  }
  mocks.admin.mockReturnValue({ from: () => query })
})
describe('shared text and voice permit selection', () => {
  it('a dropdown state resolves to its latest uploaded permit while a button can select another exact permit', () => {
    const permits = [{ id: 'old', state_code: 'LA', permit_number: 'one', created_at: '2026-01-01' }, { id: 'other', state_code: 'AL', permit_number: 'two', created_at: '2026-03-01' }, { id: 'new', state_code: 'LA', permit_number: 'three', created_at: '2026-02-01' }]
    expect(chatPermitForState(permits, 'LA')?.id).toBe('new')
    expect(chatPermitForState(permits, '')).toBeNull()
  })
  it('resolves an exact permit within this trip even when the UI state filter is stale', async () => {
    mocks.result.data = { id: 'selected', state_code: 'LA' }
    expect((await resolveChatPermit('trip', 'selected', 'LA')).permit?.id).toBe('selected')
    expect(mocks.calls).toContainEqual(['eq', 'trip_id', 'trip'])
    expect(mocks.calls).toContainEqual(['eq', 'id', 'selected'])
    expect((await resolveChatPermit('trip', 'selected', 'AL')).permit?.id).toBe('selected')
  })
  it('rejects foreign-trip permits and queries the latest permit for state-only clients', async () => {
    expect((await resolveChatPermit('trip', 'foreign', 'LA')).error).toBeTruthy()
    mocks.result.data = { id: 'latest', state_code: 'LA' }
    expect((await resolveChatPermit('trip', null, 'la')).permit?.id).toBe('latest')
    expect(mocks.calls).toContainEqual(['order', 'created_at', { ascending: false }])
    expect((await resolveChatPermit('trip')).permit).toBeNull()
  })
})
