import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { RoleSwitcherGroup } from '@/components/app/role-switcher-bar'

/**
 * The pilot testing bar used to switch the REAL signed-in session into a
 * configured test account for any role that had one (Test_Dispatcher,
 * Test_Driver, Test_Admin) — so clicking "Carrier dashboard" or "Driver app"
 * silently changed the admin's role. Nash, 2026-09-17: "when I jump between
 * dashboards, the system is changing my user role… I need to stay as an
 * admin on each dashboard."
 *
 * Fix: every item is a plain link now — `mayOpenContext` already lets an
 * internal admin open any role's pages while staying themselves. Pinned here
 * so no item can regress back into a session switch.
 */

let internalUser: { internal: boolean } | null = { internal: true }
vi.mock('@/lib/auth', () => ({ getSessionUser: async () => internalUser }))

process.env.AUTH_ROLE_SWITCH = 'true'

const { RoleSwitcher } = await import('@/components/app/role-switcher')

beforeEach(() => {
  internalUser = { internal: true }
})

function allItems(groups: RoleSwitcherGroup[]) {
  return groups.flatMap((g) => g.items)
}

describe('the pilot testing bar never switches identity', () => {
  it('every group item is a link — none carry a role to switch into', async () => {
    const el = (await RoleSwitcher({ currentRole: 'admin' })) as unknown as { props: { groups: RoleSwitcherGroup[] } }
    const items = allItems(el.props.groups)
    expect(items.length).toBeGreaterThan(0)
    expect(items.every((i) => i.kind === 'link')).toBe(true)
    // No item's shape carries a `role` to switch into (the old 'switch' kind).
    expect(items.every((i) => !('role' in i))).toBe(true)
  })

  it('covers every dashboard the bug report named, all as links', async () => {
    const el = (await RoleSwitcher({ currentRole: 'admin' })) as unknown as { props: { groups: RoleSwitcherGroup[] } }
    const items = allItems(el.props.groups)
    const byLabel = Object.fromEntries(items.map((i) => [i.label, i]))
    expect(byLabel['Carrier dashboard']).toMatchObject({ kind: 'link', href: '/cd-dashboard' })
    expect(byLabel['Driver app']).toMatchObject({ kind: 'link', href: '/ct-dashboard' })
    expect(byLabel['Broker dashboard']).toMatchObject({ kind: 'link', href: '/fb-dashboard' })
  })

  it('still hidden for a non-internal session', async () => {
    internalUser = { internal: false }
    expect(await RoleSwitcher({ currentRole: 'broker' })).toBeNull()
  })

  it('still hidden entirely when no session', async () => {
    internalUser = null
    expect(await RoleSwitcher({ currentRole: 'admin' })).toBeNull()
  })
})
