import { describe, expect, it } from 'vitest'
import { resolveDashboardRoutePolicy, roleCanAccessPolicy } from '@/lib/dashboardRoutePolicies'
import { flattenInternalRoutes, isAllowedRoute, resolveAccessRedirect } from './DashboardAccessGuard'

describe('DashboardAccessGuard route helpers', () => {
  it('normalizes dashboard-prefixed menu routes before checking access', () => {
    const routes = flattenInternalRoutes([
      {
        id: 'dashboard',
        itemType: 'INTERNAL_PAGE',
        routeOrUrl: '/dashboard',
        children: [],
      },
      {
        id: 'fleet',
        itemType: 'INTERNAL_PAGE',
        routeOrUrl: '/dashboard/fleet',
        children: [],
      },
      {
        id: 'external',
        itemType: 'EXTERNAL_LINK',
        routeOrUrl: '/dashboard/dashboard',
        children: [],
      },
    ])

    expect(routes).toEqual(['/', '/fleet'])
    expect(isAllowedRoute('/', routes)).toBe(true)
    expect(isAllowedRoute('/fleet/123', routes)).toBe(true)
  })

  it('does not redirect forever when an authenticated employee has no visible menu routes', () => {
    expect(resolveAccessRedirect('/', [])).toBeNull()
    expect(resolveAccessRedirect('/fleet', [])).toBeNull()
  })

  it('redirects disallowed routes to the first visible internal route', () => {
    expect(resolveAccessRedirect('/settings', ['/', '/fleet'])).toBe('/')
    expect(resolveAccessRedirect('/fleet/123', ['/', '/fleet'])).toBeNull()
  })

  it('treats subscription as an owner-only recovery route independent of menu registration', () => {
    const policy = resolveDashboardRoutePolicy('/subscription')

    expect(policy).toMatchObject({
      authenticationRequired: true,
      allowedRoles: ['OWNER'],
      subscriptionRequired: false,
      menuRegistrationRequired: false,
      billingRecoveryRoute: true,
    })
    expect(roleCanAccessPolicy('OWNER', policy)).toBe(true)
    expect(roleCanAccessPolicy('MANAGER', policy)).toBe(false)
    expect(roleCanAccessPolicy('AGENT', policy)).toBe(false)
  })
})
