import { MODULE_TO_BASE, PERMISSION_TRANSLATIONS, Permission, hasPermission } from '@/shared/types/permission';

export type UiAction = 'lire' | 'ecrire' | 'modifier' | 'supprimer';

const ACTION_SUFFIX: Record<UiAction, string> = {
    lire: 'READ',
    ecrire: 'WRITE',
    modifier: 'MODIFY',
    supprimer: 'DELETE',
};

function stripDiacritics(str: string): string {
    return str.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
}

function slugify(seg: string): string {
    return stripDiacritics(seg)
        .replace(/[^A-Za-z0-9]+/g, '_')
        .replace(/^_|_$/g, '')
        .toUpperCase();
}

function moduleLabelToEnumPrefix(label: string): string {
    return label
        .split('>')
        .map(s => slugify(s.trim()))
        .join('_');
}

export function resolveModulePermissions(
    moduleLabel: string,
    actionsUi: UiAction[],
): Permission[] {
    const prefix = moduleLabelToEnumPrefix(moduleLabel);

    if (actionsUi.length === 0) {
        const baseKey = prefix as keyof typeof Permission;
        return hasPermission(Permission[baseKey])
            ? [Permission[baseKey] as Permission]
            : [];
    }

    return actionsUi
        .map(a => `${prefix}_${ACTION_SUFFIX[a]}` as keyof typeof Permission)
        .filter(key => hasPermission(Permission[key]))
        .map(key => Permission[key] as Permission);
}


const valueToKey = Object.fromEntries(
    Object.entries(Permission).map(([k, v]) => [v, k])
);
export function getKeysByValues(values: string[]) {
    return values
        .map(v => valueToKey[v])
        .filter(Boolean);
}


function enumPrefixToModuleLabel(prefix: string): string {
    return prefix
        .split('_')
        .map((part) => part.charAt(0) + part.slice(1).toLowerCase())
        .join(' > ');
}

export function resolveUiActionsFromBackendPermission(permissions: string[]): UiAction[] {
    return permissions
        .map((perm) => {
            const action = perm.split('_').pop();
            return ACTION_SUFFIX[action as keyof typeof ACTION_SUFFIX] as UiAction;
        })
        .filter(Boolean);
}

export function transformModulesWithPermissions(modules: any[]): any[] {
    return modules.map((module) => {
        const uiActions = resolveUiActionsFromBackendPermission(module.permissions);

        return {
            ...module,
            permissions: uiActions,
        };
    });
}

const DEFAULT_SUB_PERMISSIONS = ['Supprimer', 'Modifier', 'Lire', 'Ecrire'];
const VALID_SUB_PERMISSIONS = ['DELETE', 'MODIFY', 'READ', 'WRITE'];

export const transformPermissionToFrontForm = (permissions: string[]) => {
    const modulesMap: Record<string, { module: string, permissions: string[], date: string }> = {};
  
    permissions.forEach((permission) => {
      const [parentModule, ...actionParts] = permission.split('_');
      const moduleName = MODULE_TO_BASE[parentModule] || 'Unknown Module';
  
      const action = actionParts[actionParts.length - 1];
      
      if (VALID_SUB_PERMISSIONS.includes(action)) {
        const translatedPermission = PERMISSION_TRANSLATIONS[action];
  
        if (!modulesMap[moduleName]) {
          modulesMap[moduleName] = {
            module: moduleName,
            permissions: [],
            date: new Date().toISOString(),
          };
        }
  
        modulesMap[moduleName].permissions.push(translatedPermission);
      }
    });
  
    return Object.values(modulesMap);
  };
  
  