import React, {createContext, useContext, useEffect} from 'react';
import {SDKConfig} from '../utils';
import {setTokenExpiryHandler} from '../services';

const SDKConfigContext = createContext<SDKConfig | null>(null);

export const SDKConfigProvider = ({
  config,
  children,
}: {
  config: SDKConfig;
  children: React.ReactNode;
}) => {
  useEffect(() => {
    // Set the global token expiry handler when the provider mounts
    setTokenExpiryHandler(config.onTokenExpired || null);

    // Cleanup when the provider unmounts
    return () => {
      setTokenExpiryHandler(null);
    };
  }, [config.onTokenExpired]);

  return (
    <SDKConfigContext.Provider value={config}>
      {children}
    </SDKConfigContext.Provider>
  );
};

export const useSDKConfig = () => {
  const context = useContext(SDKConfigContext);
  if (!context) {
    throw new Error('useSDKConfig must be used within an SDKConfigProvider');
  }
  return context;
};
