import { toDashboardAppPath } from './dashboardPaths'

export type DashboardRole = 'OWNER' | 'MANAGER' | 'AGENT'

export type DashboardRoutePolicy = {
  authenticationRequired: boolean
  allowedRoles: DashboardRole[] | null
  subscriptionRequired: boolean
  menuRegistrationRequired: boolean
  billingRecoveryRoute?: boolean
}

export const OWNER_ONLY_BILLING_RECOVERY_POLICY: DashboardRoutePolicy = {
  authenticationRequired: true,
  allowedRoles: ['OWNER'],
  subscriptionRequired: false,
  menuRegistrationRequired: false,
  billingRecoveryRoute: true,
}

export const DASHBOARD_FEATURE_POLICY: DashboardRoutePolicy = {
  authenticationRequired: true,
  allowedRoles: null,
  subscriptionRequired: true,
  menuRegistrationRequired: true,
}

export const dashboardRoutePolicies: Record<string, DashboardRoutePolicy> = {
  '/': {
    authenticationRequired: true,
    allowedRoles: null,
    subscriptionRequired: false,
    menuRegistrationRequired: false,
  },
  '/subscription': OWNER_ONLY_BILLING_RECOVERY_POLICY,
  '/subscription/success': OWNER_ONLY_BILLING_RECOVERY_POLICY,
  '/subscription/cancel': OWNER_ONLY_BILLING_RECOVERY_POLICY,
}

export function resolveDashboardRoutePolicy(pathname: string): DashboardRoutePolicy {
  const currentPath = toDashboardAppPath(pathname)
  const matchingRoute = Object.keys(dashboardRoutePolicies)
    .sort((a, b) => b.length - a.length)
    .find((route) => {
      if (route === '/') return currentPath === '/'
      return currentPath === route || currentPath.startsWith(`${route}/`)
    })

  return matchingRoute ? dashboardRoutePolicies[matchingRoute] : DASHBOARD_FEATURE_POLICY
}

export function roleCanAccessPolicy(role: string | null | undefined, policy: DashboardRoutePolicy): boolean {
  if (!policy.allowedRoles) return true
  return Boolean(role && policy.allowedRoles.includes(role as DashboardRole))
}

export function getDashboardFallbackRoute(role: string | null | undefined): string {
  if (role === 'OWNER' || role === 'MANAGER' || role === 'AGENT') return '/'
  return '/'
}
