'use client';

/**
 * 테넌트 모듈 접근 훅
 *
 * 현재 로그인한 테넌트의 활성 모듈 정보와 헬퍼 함수를 제공.
 *
 * @example
 * const { isEnabled, isRouteAllowed } = useModules();
 * if (isEnabled('production')) { ... }
 * if (isRouteAllowed('/production/work-orders')) { ... }
 */

import { useMemo } from 'react';
import { useAuthStore } from '@/stores/authStore';
import type { ModuleId } from '@/modules/types';
import { resolveEnabledModules, isModuleEnabled } from '@/modules/tenant-config';
import { getModuleForRoute, getEnabledDashboardSections } from '@/modules';

export function useModules() {
  const tenant = useAuthStore((state) => state.currentUser?.tenant);

  const enabledModules = useMemo<ModuleId[]>(() => {
    if (!tenant) return [];
    return resolveEnabledModules({
      industry: tenant.options?.industry,
      // Phase 2: explicitModules: tenant.options?.modules
    });
  }, [tenant]);

  const isEnabled = useMemo(() => {
    return (moduleId: ModuleId) => isModuleEnabled(moduleId, enabledModules);
  }, [enabledModules]);

  const isRouteAllowed = useMemo(() => {
    return (pathname: string) => {
      const owningModule = getModuleForRoute(pathname);
      if (owningModule === 'common') return true;
      return enabledModules.includes(owningModule);
    };
  }, [enabledModules]);

  const dashboardSections = useMemo(() => {
    return getEnabledDashboardSections(enabledModules);
  }, [enabledModules]);

  return {
    enabledModules,
    isEnabled,
    isRouteAllowed,
    dashboardSections,
    tenantIndustry: tenant?.options?.industry,
  };
}
