import React, { createContext, useContext, useMemo } from 'react';

// ─── Roles del sistema ───────────────────────────────────────────────────────
export const ROLES = {
  OWNER:      'OWNER',
  ADMIN:      'ADMIN',
  GERENTE:    'GERENTE',
  FINANCIERO: 'FINANCIERO',
  CONTADOR:   'CONTADOR',
  INGENIERO:  'INGENIERO',
  SUPERVISOR: 'SUPERVISOR',
  TECNICO:    'TECNICO',
};

// ─── Permisos por módulo ─────────────────────────────────────────────────────
export const PERMS = {
  // Financiero / contable
  CASH_FLOW_ALARM:      ['OWNER','ADMIN','GERENTE','FINANCIERO','CONTADOR'],
  ACCOUNTING_PAYMENTS:  ['OWNER','ADMIN','GERENTE','FINANCIERO','CONTADOR'],
  ACCOUNTING_CONTRACTS: ['OWNER','ADMIN','GERENTE','FINANCIERO','CONTADOR'],
  ACCOUNTING_NOMINA:    ['OWNER','ADMIN','FINANCIERO','CONTADOR'],
  ACCOUNTING_LIBRO:     ['OWNER','ADMIN','FINANCIERO','CONTADOR'],
  ACCOUNTING_FLUJO:     ['OWNER','ADMIN','GERENTE','FINANCIERO','CONTADOR'],
  BUDGET:               ['OWNER','ADMIN','GERENTE','FINANCIERO','CONTADOR','INGENIERO'],
  REPORTS_FINANCIAL:    ['OWNER','ADMIN','GERENTE','FINANCIERO','CONTADOR'],
  REPORTS_OPERATIONAL:  ['OWNER','ADMIN','GERENTE','FINANCIERO','CONTADOR','INGENIERO','SUPERVISOR'],
  PROCUREMENT:          ['OWNER','ADMIN','GERENTE','FINANCIERO','CONTADOR'],
  // Gestión
  PROJECTS:             ['OWNER','ADMIN','GERENTE','INGENIERO','SUPERVISOR'],
  TASKS:                ['OWNER','ADMIN','GERENTE','INGENIERO','SUPERVISOR','TECNICO'],
  TEAM:                 ['OWNER','ADMIN','GERENTE'],
  // Sistema
  USERS_ROLES:          ['OWNER','ADMIN'],
  SETTINGS:             ['OWNER','ADMIN'],
};

// ─── Función utilitaria pura ─────────────────────────────────────────────────
export function can(permKey, userRole) {
  const allowed = PERMS[permKey];
  if (!allowed) return false;
  return allowed.includes(userRole);
}

// ─── Context ─────────────────────────────────────────────────────────────────
const PermissionsContext = createContext(null);

export function PermissionsProvider({ children }) {
  // Lee el rol desde localStorage; en prod vendría del AuthContext/user.role
  const role = useMemo(() => {
    try {
      return localStorage.getItem('arpm_user_role') || 'OWNER';
    } catch {
      return 'OWNER';
    }
  }, []);

  const value = useMemo(() => ({
    role,
    can: (permKey) => can(permKey, role),
    isOwner:     role === 'OWNER',
    isAdmin:     role === 'ADMIN' || role === 'OWNER',
    isFinancial: ['OWNER','ADMIN','FINANCIERO','CONTADOR'].includes(role),
  }), [role]);

  return (
    <PermissionsContext.Provider value={value}>
      {children}
    </PermissionsContext.Provider>
  );
}

export function usePermissions() {
  const ctx = useContext(PermissionsContext);
  if (!ctx) throw new Error('usePermissions must be inside PermissionsProvider');
  return ctx;
}
