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

export type UiAction = "Lire" | "Écrire" | "Modifier" | "Supprimer"

const ACTION_SUFFIX: Record<UiAction, string> = {
  Lire: "READ",
  Écrire: "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("_")
}

// Clean the user-facing menu label before permission comparison
 function normalizeMenuLabelForPermission(label: string): string {
  return label
    // Handle French elisions BEFORE stripping apostrophes:
    .replace(/\b(?:[cdjlmnst]|qu|jusqu|lorsqu|puisqu|quelqu)['’]\s*/gi, " ")
    .normalize("NFD").replace(/[\u0300-\u036f]/g, "") // remove accents
    .replace(/[>/]/g, " ")                            // split separators
    .replace(/[\u2019']/g, "")                        // remove remaining apostrophes
    .toLowerCase()
    .replace(/\b(l|d)\b/g, "")                        // leftover single letters
    .replace(/\b(de|du|des|et|la|le|les|au|aux|a|à|pour|sur|en)\b/g, " ")
    .replace(/\s+/g, " ")                             // collapse spaces
    .trim();
}

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

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

    // 2) If we do not find our ,odule we rebuild a prefix, retry
    const normalized = normalizeMenuLabelForPermission(moduleLabel)                  //  "Facturation et Paiement" BECOMES "facturation paiement"
    const fallbackPrefix = moduleLabelToEnumPrefix(normalized);          
    const fbBaseKey = fallbackPrefix as keyof typeof Permission
    return hasPermission(Permission[fbBaseKey]) ? [Permission[fbBaseKey] as Permission] : []
  }

  
  // Permission with actions: exact labels
  const resolvedExact = actionsUi
    .map((a) => {
      const permissionKey = `${prefix}_${ACTION_SUFFIX[a]}` as keyof typeof Permission
      return hasPermission(Permission[permissionKey]) ? (Permission[permissionKey] as Permission) : null
    })
    .filter((p): p is Permission => p !== null)

  if (resolvedExact.length > 0) return resolvedExact

  // Permission with actions: we do it again with normalized label
  const normalized = normalizeMenuLabelForPermission(moduleLabel)
  const fallbackPrefix = moduleLabelToEnumPrefix(normalized);            
  const resolvedFallback = actionsUi
    .map((a) => {
      const permissionKey = `${fallbackPrefix}_${ACTION_SUFFIX[a]}` as keyof typeof Permission
      return hasPermission(Permission[permissionKey]) ? (Permission[permissionKey] as Permission) : null
    })
    .filter((p): p is Permission => p !== null)

  //THIS REBUILDING is BECAUSE OF TERMS LIKE : 'et', 'de', '`'....

  return resolvedFallback
}


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[] {
  const reverseActionSuffix: Record<string, UiAction> = {
    READ: "Lire",
    WRITE: "Écrire",
    MODIFY: "Modifier",
    DELETE: "Supprimer",
  }

  return permissions
    .map((perm) => {
      const action = perm.split("_").pop()
      return reverseActionSuffix[action as keyof typeof reverseActionSuffix]
    })
    .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", "Écrire"]
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)
}
