import * as _ from 'lodash';

import { GetControlplaneEndpoint } from 'dashboard/core/utils/env';
import { createFeatureFlags } from 'dashboard/generated/controlplane/twirp';

const featureFlagCache: { [key: string]: boolean } = { };

export async function featureFlagInit() {
  const client = createFeatureFlags(GetControlplaneEndpoint());
  try {
    const { featureFlags } = await (await client.list({})).toJSON();
    _.each(featureFlags, (featureFlag) => {
      featureFlagCache[featureFlag.name] = featureFlag.isEnabled;
    });
  } catch (err) {
    // Swallow errors if we fail to load feature flags. This will cause all feature flags to default to false.
  }
}

export function featureFlagIsEnabled(name: string): boolean {
  return featureFlagCache[name] || false;
}
