import { describe, expect, it } from 'vitest'
import { isInternalRole, isInternalUser } from '@/lib/domain/roles'
import { dashboardRole, isDriverOnTrip } from '@/lib/role-view'
import type { TripParticipant } from '@/types/db'

/**
 * Task 96 (2026-09-09): pilot bars, design previews and the `?view=` override
 * are internal-only. These are security-relevant — the override decides which
 * role's screen a request is served — so the rules are pinned here.
 */

describe('isInternalRole', () => {
  it('accepts admin only', () => {
    expect(isInternalRole('admin')).toBe(true)
    expect(isInternalRole('broker')).toBe(false)
    expect(isInternalRole('dispatcher')).toBe(false)
    expect(isInternalRole('driver')).toBe(false)
  })
  it('is safe on missing values', () => {
    expect(isInternalRole(null)).toBe(false)
    expect(isInternalRole(undefined)).toBe(false)
    expect(isInternalRole('')).toBe(false)
    expect(isInternalUser(null)).toBe(false)
  })
})

describe('dashboardRole — ?view= is internal-only', () => {
  it('ignores the override for a customer', () => {
    expect(dashboardRole('driver', 'broker', false)).toBe('broker')
    expect(dashboardRole('admin', 'dispatcher', false)).toBe('dispatcher')
    // Default parameter: absent means not internal.
    expect(dashboardRole('driver', 'broker')).toBe('broker')
  })
  it('honours the override for internal staff', () => {
    expect(dashboardRole('driver', 'admin', true)).toBe('driver')
    expect(dashboardRole('carrier', 'admin', true)).toBe('dispatcher')
  })
  it('falls back to the account role when no view is given', () => {
    expect(dashboardRole(undefined, 'dispatcher', true)).toBe('dispatcher')
    expect(dashboardRole(undefined, 'driver', false)).toBe('driver')
    expect(dashboardRole(undefined, 'admin', true)).toBe('broker')
  })
})

describe('isDriverOnTrip — the driver view still works without the override', () => {
  const asDriver = { role: 'driver' } as TripParticipant
  const asBroker = { role: 'broker' } as TripParticipant

  it('keeps a real driver in the driver view even though ?view= is ignored', () => {
    // The driver interface links carry ?view=driver (Task 78); a real driver
    // resolves through their participant role, so the links keep working.
    expect(isDriverOnTrip('driver', asDriver, 'driver', false)).toBe(true)
    expect(isDriverOnTrip(undefined, asDriver, 'driver', false)).toBe(true)
  })
  it('does not let a customer preview the driver view', () => {
    expect(isDriverOnTrip('driver', asBroker, 'broker', false)).toBe(false)
  })
  it('lets internal staff preview it', () => {
    expect(isDriverOnTrip('driver', asBroker, 'admin', true)).toBe(true)
  })
  it('falls back to the account role with no participant row', () => {
    expect(isDriverOnTrip(undefined, null, 'driver', false)).toBe(true)
    expect(isDriverOnTrip(undefined, null, 'broker', false)).toBe(false)
  })
})
