import type { UserRole, RolePermissions } from '../types'

export const ROLE_PERMISSIONS: Record<UserRole, RolePermissions> = {
  user: {
    canManageEvents: false,
    canManageUsers: false,
    canManageOrganization: false,
    canAccessAdminPanel: false,
    canManageTerritories: false,
    canViewAnalytics: false,
    canManagePayments: false,
  },
  admin: {
    canManageEvents: true,
    canManageUsers: true,
    canManageOrganization: true,
    canAccessAdminPanel: true,
    canManageTerritories: false,
    canViewAnalytics: true,
    canManagePayments: true,
  },
  super_admin: {
    canManageEvents: true,
    canManageUsers: true,
    canManageOrganization: true,
    canAccessAdminPanel: true,
    canManageTerritories: true,
    canViewAnalytics: true,
    canManagePayments: true,
  },
  territory_manager: {
    canManageEvents: true,
    canManageUsers: false,
    canManageOrganization: false,
    canAccessAdminPanel: false,
    canManageTerritories: true,
    canViewAnalytics: true,
    canManagePayments: false,
  },
}

export function hasPermission(role: UserRole, permission: keyof RolePermissions): boolean {
  return ROLE_PERMISSIONS[role]?.[permission] ?? false
}

export function hasRole(userRole: UserRole, requiredRole: UserRole): boolean {
  const roleHierarchy: Record<UserRole, number> = {
    user: 0,
    admin: 1,
    territory_manager: 1,
    super_admin: 2,
  }

  return roleHierarchy[userRole] >= roleHierarchy[requiredRole]
}

export function hasAnyRole(userRole: UserRole, requiredRoles: UserRole[]): boolean {
  return requiredRoles.some(role => hasRole(userRole, role))
}

export function hasAllPermissions(role: UserRole, permissions: (keyof RolePermissions)[]): boolean {
  return permissions.every(permission => hasPermission(role, permission))
}

export function hasAnyPermission(role: UserRole, permissions: (keyof RolePermissions)[]): boolean {
  return permissions.some(permission => hasPermission(role, permission))
}

export function getRolePermissions(role: UserRole): RolePermissions {
  return ROLE_PERMISSIONS[role] || ROLE_PERMISSIONS.user
}

export function canAccessResource(userRole: UserRole, resourcePermissions: (keyof RolePermissions)[]): boolean {
  return hasAllPermissions(userRole, resourcePermissions)
}

export function isAdmin(role: UserRole): boolean {
  return hasRole(role, 'admin')
}

export function isSuperAdmin(role: UserRole): boolean {
  return role === 'super_admin'
}

export function isTerritoryManager(role: UserRole): boolean {
  return role === 'territory_manager'
}