'use client';

import { useEffect } from 'react';
import { usePathname } from 'next/navigation';
import { usePermissionStore } from '@/stores/permissionStore';
import { findMatchingUrl } from '@/lib/permissions/utils';
import type { PermissionMap, PermissionAction } from '@/lib/permissions/types';
import { AccessDenied } from '@/components/common/AccessDenied';
import { stripLocalePrefix } from '@/lib/utils/locale';

/**
 * PermissionProvider — Zustand store 초기화 래퍼
 *
 * 기존 Context.Provider 역할을 대체합니다.
 * 마운트 시 한 번 loadPermissions() 호출만 담당합니다.
 */
export function PermissionProvider({ children }: { children: React.ReactNode }) {
  const loadPermissions = usePermissionStore((s) => s.loadPermissions);

  useEffect(() => {
    loadPermissions();
  }, [loadPermissions]);

  return <>{children}</>;
}

/**
 * 자기 잠금(self-lockout) 방지: 권한 설정 페이지는 항상 접근 허용
 */
const BYPASS_PATHS = ['/settings/permissions'];

function isGateBypassed(pathname: string): boolean {
  const pathWithoutLocale = stripLocalePrefix(pathname);
  return BYPASS_PATHS.some((bp) => pathWithoutLocale.startsWith(bp));
}

/**
 * PermissionGate: 레이아웃에 배치하여 모든 페이지 자동 보호
 */
export function PermissionGate({ children }: { children: React.ReactNode }) {
  const pathname = usePathname();
  const permissionMap = usePermissionStore((s) => s.permissionMap);
  const isLoading = usePermissionStore((s) => s.isLoading);

  if (isLoading) return null;
  if (!permissionMap) {
    return <>{children}</>;
  }

  if (isGateBypassed(pathname)) return <>{children}</>;

  const matchedUrl = findMatchingUrl(pathname, permissionMap);

  if (!matchedUrl) {
    return <>{children}</>;
  }

  const perms = permissionMap[matchedUrl];
  const canView = perms?.view ?? true;

  if (!canView) {
    return <AccessDenied />;
  }

  return <>{children}</>;
}

/**
 * 하위호환 훅 — 기존 usePermissionContext() 소비자를 위한 어댑터
 *
 * Zustand store에서 읽되, 기존과 동일한 인터페이스를 반환합니다.
 */
export function usePermissionContext(): {
  permissionMap: PermissionMap | null;
  isLoading: boolean;
  can: (url: string, action: PermissionAction) => boolean;
  reloadPermissions: () => void;
} {
  const permissionMap = usePermissionStore((s) => s.permissionMap);
  const isLoading = usePermissionStore((s) => s.isLoading);
  const can = usePermissionStore((s) => s.can);
  const loadPermissions = usePermissionStore((s) => s.loadPermissions);

  return { permissionMap, isLoading, can, reloadPermissions: loadPermissions };
}
