'use client';

import React, { createContext, useContext, useEffect, useState, ReactNode } from 'react';

export interface RuntimeConfig {
  apiUrl: string;
  backofficeUrl: string;
  seederApiUrl: string;
  scraperApiUrl: string;
}

const defaultConfig: RuntimeConfig = {
  apiUrl: process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8521',
  backofficeUrl: process.env.NEXT_PUBLIC_BACKOFFICE_URL || 'http://localhost:3001',
  seederApiUrl: process.env.NEXT_PUBLIC_SEEDER_API_URL || 'http://localhost:3002',
  scraperApiUrl: process.env.NEXT_PUBLIC_SCRAPER_API_URL || 'http://localhost:3003',
};

interface ConfigContextType {
  config: RuntimeConfig;
  isLoading: boolean;
}

const ConfigContext = createContext<ConfigContextType>({
  config: defaultConfig,
  isLoading: true,
});

export function ConfigProvider({ children }: { children: ReactNode }) {
  const [config, setConfig] = useState<RuntimeConfig>(defaultConfig);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    async function fetchConfig() {
      try {
        const response = await fetch('/api/config');
        if (response.ok) {
          const data = await response.json();
          console.log('[Config] Loaded runtime config:', data);
          setConfig(data);
          // Also update the global cached config for non-React usage
          cachedConfig = data;
        }
      } catch (error) {
        console.warn('[Config] Failed to fetch runtime config, using defaults:', error);
      } finally {
        setIsLoading(false);
      }
    }

    fetchConfig();
  }, []);

  return (
    <ConfigContext.Provider value={{ config, isLoading }}>
      {children}
    </ConfigContext.Provider>
  );
}

export function useConfig(): RuntimeConfig {
  const { config } = useContext(ConfigContext);
  return config;
}

export function useConfigContext(): ConfigContextType {
  return useContext(ConfigContext);
}

// Helper function for non-React contexts (like lib files)
// This returns a promise that resolves to the config
let cachedConfig: RuntimeConfig | null = null;

export async function getConfig(): Promise<RuntimeConfig> {
  if (cachedConfig) return cachedConfig;

  try {
    const response = await fetch('/api/config');
    if (response.ok) {
      cachedConfig = await response.json();
      return cachedConfig!;
    }
  } catch {
    console.warn('[Config] Failed to fetch config, using defaults');
  }

  return defaultConfig;
}

// Sync getter for when you need immediate access (uses cached or default)
export function getConfigSync(): RuntimeConfig {
  return cachedConfig || defaultConfig;
}
