import { LOCALHOST_MODE, STORAGE_MEMORY } from '@splitsoftware/splitio-commons/src/utils/constants';

const STORAGE_LOCALSTORAGE = 'LOCALSTORAGE';

export function validateStorage(settings) {
  let {
    log,
    mode,
    storage: {
      type,
      options = {},
      prefix,
      expirationDays,
      clearOnInit,
      wrapper
    } = { type: STORAGE_MEMORY },
  } = settings;
  let __originalType;

  const fallbackToMemory = () => {
    __originalType = type;
    type = STORAGE_MEMORY;
  };

  // In localhost mode, fallback to Memory storage and track original type to emit SDK_READY_FROM_CACHE if corresponds.
  // ATM, other mode settings (e.g., 'consumer') are ignored in client-side API, and so treated as standalone.
  if (mode === LOCALHOST_MODE && type === STORAGE_LOCALSTORAGE) {
    fallbackToMemory();
  }

  // If an invalid storage type is provided, fallback into MEMORY
  if (type !== STORAGE_MEMORY && type !== STORAGE_LOCALSTORAGE) {
    fallbackToMemory();
    log.error('Invalid storage type. Fallback into MEMORY storage');
  }

  return {
    type,
    options,
    prefix,
    expirationDays,
    clearOnInit,
    wrapper,
    __originalType
  };
}
