import { Injectable } from '@angular/core';

export interface ModulePermission {
  module: string;
  roles: string[];
  children?: { [key: string]: string[] };
}

@Injectable({ providedIn: 'root' })
export class PermissionsService {
  private readonly permissions: ModulePermission[] = [
    // Dashboard
    {
      module: 'dcb-dashboard',
      roles: ['admin', 'merchant', 'support'],
    },

    // Transactions
    {
      module: 'transactions',
      roles: ['admin', 'merchant', 'support'],
    },

    // Merchants
    {
      module: 'merchants',
      roles: ['admin', 'merchant'],
      children: {
        'list': ['admin'],
        'config': ['admin', 'merchant'],
        'history': ['admin', 'merchant']
      }
    },

    // Operators (Admin only)
    {
      module: 'operators',
      roles: ['admin'],
      children: {
        'config': ['admin'],
        'stats': ['admin']
      }
    },

    // Webhooks
    {
      module: 'webhooks',
      roles: ['admin', 'merchant'],
      children: {
        'history': ['admin', 'merchant'],
        'status': ['admin', 'merchant'],
        'retry': ['admin']
      }
    },

    // Users (Admin only)
    {
      module: 'users',
      roles: ['admin']
    },

    // Support (All authenticated users)
    {
      module: 'settings',
      roles: ['admin', 'merchant', 'support']
    },

    // Integrations (Admin only)
    {
      module: 'integrations',
      roles: ['admin']
    },

    // Support (All authenticated users)
    {
      module: 'support',
      roles: ['admin', 'merchant', 'support']
    },

    // Profile (All authenticated users)
    {
      module: 'profile',
      roles: ['admin', 'merchant', 'support']
    },

    // Documentation (All authenticated users)
    {
      module: 'documentation',
      roles: ['admin', 'merchant', 'support']
    },

    // Help (All authenticated users)
    {
      module: 'help',
      roles: ['admin', 'merchant', 'support']
    },

    // About (All authenticated users)
    {
      module: 'about',
      roles: ['admin', 'merchant', 'support']
    }
  ];

  canAccessModule(modulePath: string, userRoles: string[]): boolean {
    if (!userRoles || userRoles.length === 0) {
      return false;
    }

    const [mainModule, subModule] = modulePath.split('/');
    const permission = this.findPermission(mainModule);

    if (!permission) {
      console.warn(`No permission configuration for module: ${mainModule}`);
      return false;
    }

    // Check main module access
    const hasModuleAccess = this.hasAnyRole(permission.roles, userRoles);
    if (!hasModuleAccess) return false;

    // Check sub-module access if specified
    if (subModule && permission.children) {
      const subModuleRoles = permission.children[subModule];
      if (!subModuleRoles) {
        console.warn(`No permission configuration for submodule: ${mainModule}/${subModule}`);
        return false;
      }
      return this.hasAnyRole(subModuleRoles, userRoles);
    }

    return true;
  }

  private findPermission(module: string): ModulePermission | undefined {
    return this.permissions.find(p => p.module === module);
  }

  private hasAnyRole(requiredRoles: string[], userRoles: string[]): boolean {
    return requiredRoles.some(role => userRoles.includes(role));
  }

  getAccessibleModules(userRoles: string[]): string[] {
    return this.permissions
      .filter(permission => this.hasAnyRole(permission.roles, userRoles))
      .map(permission => permission.module);
  }
}