/**
 * RBAC Permissions
 *
 * Defines the permission constants and role-permission mappings
 * for the customer portal authorization system.
 */

export const PERMISSIONS = {
  // Account permissions
  ACCOUNT_READ: "account:read",
  ACCOUNT_UPDATE: "account:update",

  // Billing permissions
  BILLING_READ: "billing:read",
  BILLING_PAY: "billing:pay",

  // Orders permissions
  ORDERS_READ: "orders:read",
  ORDERS_CREATE: "orders:create",

  // Services permissions
  SERVICES_READ: "services:read",
  SERVICES_MANAGE: "services:manage",

  // Support permissions
  SUPPORT_READ: "support:read",
  SUPPORT_CREATE: "support:create",

  // Admin permissions
  ADMIN_USERS: "admin:users",
  ADMIN_AUDIT: "admin:audit",
} as const;

export type Permission = (typeof PERMISSIONS)[keyof typeof PERMISSIONS];

export const ROLE_PERMISSIONS: Record<string, Permission[]> = {
  USER: [
    PERMISSIONS.ACCOUNT_READ,
    PERMISSIONS.ACCOUNT_UPDATE,
    PERMISSIONS.BILLING_READ,
    PERMISSIONS.BILLING_PAY,
    PERMISSIONS.ORDERS_READ,
    PERMISSIONS.ORDERS_CREATE,
    PERMISSIONS.SERVICES_READ,
    PERMISSIONS.SERVICES_MANAGE,
    PERMISSIONS.SUPPORT_READ,
    PERMISSIONS.SUPPORT_CREATE,
  ],
  ADMIN: Object.values(PERMISSIONS) as Permission[],
};

/**
 * Check if a role has a specific permission
 */
export function hasPermission(role: string, permission: Permission): boolean {
  const rolePermissions = ROLE_PERMISSIONS[role];
  if (!rolePermissions) {
    return false;
  }
  return rolePermissions.includes(permission);
}

/**
 * Check if a role has any of the specified permissions
 */
export function hasAnyPermission(role: string, permissions: Permission[]): boolean {
  return permissions.some(permission => hasPermission(role, permission));
}

/**
 * Check if a role has all of the specified permissions
 */
export function hasAllPermissions(role: string, permissions: Permission[]): boolean {
  return permissions.every(permission => hasPermission(role, permission));
}

/**
 * Get all permissions for a role
 */
export function getPermissionsForRole(role: string): Permission[] {
  return ROLE_PERMISSIONS[role] ?? [];
}
