import { ReactNode, useEffect } from 'react';
import { Navigate } from 'react-router-dom';
import { useSettingsStore } from '../../store/settingsStore';
import { isModuleEnabled } from '../../config/modules.config';
import { isUpgradeError } from '../../utils/upgrade';

interface ModuleGuardProps {
  module: string;
  children: ReactNode;
  redirectTo?: string;
}

/**
 * ModuleGuard - Protects routes based on module enable status
 * Redirects to settings page if module is disabled
 */
export default function ModuleGuard({ module, children, redirectTo = '/settings/modules' }: ModuleGuardProps) {
  const { moduleEnableSettings, loadModuleEnableSettings, loading } = useSettingsStore();

  useEffect(() => {
    // Load module enable settings if not already loaded
    if (!moduleEnableSettings && !loading) {
      loadModuleEnableSettings();
    }
  }, [moduleEnableSettings, loading, loadModuleEnableSettings]);

  // While loading, show children (optimistic rendering)
  if (loading || !moduleEnableSettings) {
    return <>{children}</>;
  }

  // Check if module is enabled
  const enabled = isModuleEnabled(module, moduleEnableSettings as any);

  if (!enabled) {
    return <Navigate to={redirectTo} replace />;
  }

  return <>{children}</>;
}

