// [TSM.ID].[11031972] -- All Rights Reserved. Proprietary & Confidential.
// Dynamic Module Registry Context — Fetches from XCU API Gateway
// Fallback to STATIC_MODULE_REGISTRY if API offline

import { createContext, useContext, useState, useEffect, useCallback } from 'react';
import { STATIC_MODULE_REGISTRY } from '../config/ModuleRegistry';

const ModuleRegistryContext = createContext();

const API_BASE = import.meta.env.VITE_XCU_API_URL || '';

export function ModuleRegistryProvider({ children }) {
  const [registry, setRegistry] = useState(STATIC_MODULE_REGISTRY);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [source, setSource] = useState('STATIC'); // 'API' or 'STATIC'

  const fetchRegistry = useCallback(async () => {
    try {
      setLoading(true);
      const res = await fetch(`${API_BASE}/xcu-api/v1/modules`);
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      const data = await res.json();
      setRegistry(data);
      setSource('API');
      setError(null);
      console.log('[XCU REGISTRY] Loaded from API Gateway (xcu_iam PostgreSQL)');
    } catch (err) {
      console.warn('[XCU REGISTRY] API offline, using static fallback:', err.message);
      setRegistry(STATIC_MODULE_REGISTRY);
      setSource('STATIC');
      setError(err.message);
    } finally {
      setLoading(false);
    }
  }, []);

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

  // Flat array of all modules
  const allModules = Object.values(registry).reduce((acc, group) => {
    return acc.concat(group.modules || []);
  }, []);

  // Total count
  const totalModules = allModules.length;

  // Lookup helper: find module name by ID
  const getModuleName = useCallback((modId) => {
    for (const groupKey in registry) {
      const found = registry[groupKey].modules.find(m => m.id === modId);
      if (found) return found.name;
    }
    return modId;
  }, [registry]);

  // Lookup helper: find full module details
  const getModuleDetails = useCallback((modId) => {
    for (const groupKey in registry) {
      const found = registry[groupKey].modules.find(m => m.id === modId);
      if (found) return { ...found, groupKey, groupName: registry[groupKey].name };
    }
    return { id: modId, name: `Unknown: ${modId}` };
  }, [registry]);

  // CRUD: Add module
  const addModule = useCallback(async (moduleData) => {
    try {
      const res = await fetch(`${API_BASE}/xcu-api/v1/modules`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(moduleData)
      });
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      await fetchRegistry(); // Refresh
      return true;
    } catch (err) {
      console.error('[XCU REGISTRY] Add module failed:', err.message);
      return false;
    }
  }, [fetchRegistry]);

  // CRUD: Delete (deactivate) module
  const deleteModule = useCallback(async (moduleId) => {
    try {
      const res = await fetch(`${API_BASE}/xcu-api/v1/modules/${moduleId}`, {
        method: 'DELETE'
      });
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      await fetchRegistry(); // Refresh
      return true;
    } catch (err) {
      console.error('[XCU REGISTRY] Delete module failed:', err.message);
      return false;
    }
  }, [fetchRegistry]);

  return (
    <ModuleRegistryContext.Provider value={{
      registry,
      allModules,
      totalModules,
      loading,
      error,
      source,
      getModuleName,
      getModuleDetails,
      addModule,
      deleteModule,
      refreshRegistry: fetchRegistry,
    }}>
      {children}
    </ModuleRegistryContext.Provider>
  );
}

export function useModuleRegistry() {
  const ctx = useContext(ModuleRegistryContext);
  if (!ctx) {
    throw new Error('useModuleRegistry must be used within ModuleRegistryProvider');
  }
  return ctx;
}
