
import { usePathname } from 'next/navigation';
import { usePermissionStore } from '@/stores/permissionStore';
import { findMatchingUrl } from '@/lib/permissions/utils';
import { ALL_ALLOWED } from '@/lib/permissions/types';
import type { UsePermissionReturn } from '@/lib/permissions/types';

/**
 * URL 자동매칭 권한 훅
 *
 * 인자 없이 호출하면 현재 URL 기반 자동 매칭.
 * 특수 케이스에서 URL 직접 지정 가능.
 *
 * @example
 * // 자동 매칭 (대부분의 경우)
 * const { canView, canCreate, canUpdate, canDelete } = usePermission();
 *
 * // URL 직접 지정 (다른 메뉴 권한 체크 시)
 * const { canApprove } = usePermission('/approval/inbox');
 */
export function usePermission(overrideUrl?: string): UsePermissionReturn {
  const pathname = usePathname();
  const permissionMap = usePermissionStore((s) => s.permissionMap);
  const isLoading = usePermissionStore((s) => s.isLoading);

  const targetPath = overrideUrl || pathname;

  if (isLoading || !permissionMap) {
    return { ...ALL_ALLOWED, isLoading };
  }

  const matchedUrl = findMatchingUrl(targetPath, permissionMap);

  if (!matchedUrl) {
    return ALL_ALLOWED;
  }

  const perms = permissionMap[matchedUrl] || {};

  return {
    canView: perms.view ?? true,
    canCreate: perms.create ?? true,
    canUpdate: perms.update ?? true,
    canDelete: perms.delete ?? true,
    canApprove: perms.approve ?? true,
    canExport: perms.export ?? true,
    isLoading: false,
    matchedUrl,
  };
}
