import {
  createContext as createReactContext,
  useContext as useReactContext,
} from 'react';

export function assertContextValue(
  contextName: string,
  value: unknown,
): asserts value {
  if (process.env.NODE_ENV !== 'production' && !value) {
    throw new Error(`${contextName}: value was not provided`);
  }
}

export function createContext<T>(contextName: string) {
  const Context = createReactContext<T | null>(null);

  const Provider = Context.Provider;
  const Consumer = Context.Consumer;

  const useContext = () => {
    const value = useReactContext(Context);
    assertContextValue(contextName, value);
    return value;
  };

  return {
    Context,
    Provider,
    Consumer,
    useContext,
  };
}
