import { PERMISSION_ACTIONS } from './types';
import type { PermissionMap } from './types';
import { stripLocalePrefix } from '@/lib/utils/locale';

interface SerializableMenuItem {
  id: string;
  path: string;
  children?: SerializableMenuItem[];
}

/**
 * localStorage 메뉴 트리에서 menuId → URL 매핑 생성
 */
export function buildMenuIdToUrlMap(menus: SerializableMenuItem[]): Record<string, string> {
  const map: Record<string, string> = {};

  function traverse(items: SerializableMenuItem[]) {
    for (const item of items) {
      if (item.id && item.path) {
        map[item.id] = item.path;
      }
      if (item.children?.length) {
        traverse(item.children);
      }
    }
  }

  traverse(menus);
  return map;
}

/**
 * 설정 페이지 API 응답(menuId 기반) → URL 기반 PermissionMap 변환
 *
 * API 응답: { permissions: { [menuId]: { view: true, create: false, ... } } }
 * 결과:     { "/boards/free": { view: true, create: false, ... } }
 */
export function convertMatrixToPermissionMap(
  permissions: Record<string, Record<string, boolean>>,
  menuIdToUrl: Record<string, string>
): PermissionMap {
  const map: PermissionMap = {};

  for (const [menuId, perms] of Object.entries(permissions)) {
    const url = menuIdToUrl[menuId];
    if (!url) continue; // URL 매핑 없는 메뉴 스킵

    map[url] = {};
    for (const action of PERMISSION_ACTIONS) {
      // API는 허용된 권한만 포함, 누락된 action = 비허용(false)
      map[url][action] = perms[action] === true;
    }
  }

  return map;
}

/**
 * 다중 역할 PermissionMap 병합 (Union: 하나라도 허용이면 허용)
 */
export function mergePermissionMaps(maps: PermissionMap[]): PermissionMap {
  if (maps.length === 0) return {};
  if (maps.length === 1) return maps[0];

  const merged: PermissionMap = {};
  const allUrls = new Set(maps.flatMap(m => Object.keys(m)));

  for (const url of allUrls) {
    merged[url] = {};
    for (const action of PERMISSION_ACTIONS) {
      const values = maps
        .map(m => m[url]?.[action])
        .filter((v): v is boolean => v !== undefined);
      if (values.length > 0) {
        merged[url][action] = values.some(v => v);
      }
    }
  }

  return merged;
}

/**
 * Longest prefix match: 현재 경로에서 가장 길게 매칭되는 권한 URL 찾기
 */
export function findMatchingUrl(currentPath: string, permissionMap: PermissionMap): string | null {
  const pathWithoutLocale = stripLocalePrefix(currentPath);

  if (permissionMap[pathWithoutLocale]) {
    return pathWithoutLocale;
  }

  const segments = pathWithoutLocale.split('/').filter(Boolean);
  for (let i = segments.length; i > 0; i--) {
    const prefix = '/' + segments.slice(0, i).join('/');
    if (permissionMap[prefix]) {
      return prefix;
    }
  }

  return null;
}
