import { Ref, ref } from 'vue';
import { FeatureFlipperFeatures } from './featureFlipper.model';

const features: Ref<FeatureFlipperFeatures> = ref({});

export const useFeatureFlipper = () => {
  const isFeatureEnabled = (name: string): boolean => {
    if (
      import.meta.env.STORYBOOK === 'true' ||
      import.meta.env.VITE_CYPRESS === 'true'
    ) {
      return true;
    }
    return features.value[name] || false;
  };

  const fetchFeatures = () => {
    const storage = getFeaturesFromStorage();
    features.value = Object.keys(features.value).reduce(
      (accumulator, featureName) => {
        accumulator[featureName] =
          storage[featureName] === undefined
            ? features.value[featureName]
            : storage[featureName];
        return accumulator;
      },
      {} as FeatureFlipperFeatures,
    );
  };

  const setFeaturesInStorage = (features: FeatureFlipperFeatures) => {
    localStorage.setItem('features', JSON.stringify(features));
  };

  const getFeaturesFromStorage = () => {
    try {
      return JSON.parse(localStorage.getItem('features') || '{}');
    } catch (e) {
      return {};
    }
  };

  const toggleFeature = (featureName: string) => {
    if (features.value[featureName] !== undefined) {
      features.value[featureName] = !features.value[featureName];
      setFeaturesInStorage(features.value);
    }
  };

  const resetFeatures = (initFeatures: FeatureFlipperFeatures) => {
    features.value = { ...initFeatures };
  };

  const initFeatures = (initFeatures: FeatureFlipperFeatures) => {
    resetFeatures(initFeatures);
    fetchFeatures();
    setFeaturesInStorage(features.value);
  };

  return {
    isFeatureEnabled,
    toggleFeature,
    fetchFeatures,
    resetFeatures,
    initFeatures,
    features,
  };
};
