import { describe, expect, it } from 'vitest'
import { canUsePurchasing } from '@/lib/domain/purchasing-access'

/** Nash, 2026-10-01: Billing and the buy-route / buy-permit controls are for admin and moderator only. */
describe('canUsePurchasing', () => {
  it('allows an admin account', () => {
    expect(canUsePurchasing({ role: 'admin', internal: true, surfaces: [] })).toBe(true)
  })
  it('allows an admin who switched into a test account', () => {
    expect(canUsePurchasing({ role: 'driver', internal: true, surfaces: [] })).toBe(true)
  })
  it('allows a moderator — a person granted at least one moderator page', () => {
    expect(canUsePurchasing({ role: 'dispatcher', internal: false, surfaces: ['moderation'] })).toBe(true)
  })
  it.each(['broker', 'dispatcher', 'driver'])('refuses a %s customer', (role) => {
    expect(canUsePurchasing({ role, internal: false, surfaces: [] })).toBe(false)
    expect(canUsePurchasing({ role, internal: false })).toBe(false)
  })
  it('refuses when nobody is signed in', () => {
    expect(canUsePurchasing(null)).toBe(false)
    expect(canUsePurchasing(undefined)).toBe(false)
  })
})

describe('purchase controls on screen', () => {
  it('draws nothing for a customer and the control for an admin or moderator', async () => {
    const { createElement } = await import('react')
    const { renderToString } = await import('react-dom/server')
    const { PurchasingAccessProvider, PurchasingOnly } = await import('@/components/app/purchasing-access')
    const control = createElement(PurchasingOnly, null, createElement('button', null, 'Buy route'))
    expect(renderToString(control)).not.toContain('Buy route')
    expect(renderToString(createElement(PurchasingAccessProvider, { allowed: false }, control))).not.toContain('Buy route')
    expect(renderToString(createElement(PurchasingAccessProvider, { allowed: true }, control))).toContain('Buy route')
  })
})
