import {
  ExperimentOverrideMapping,
  ExperimentUUIDs,
  ExperimentGroups,
} from 'mweb/common/actions/experiments';
import { Enum } from 'mweb/common/utils/enum';

/**
 * Parse the query parameter "experiment_overrides" to explicitly set experiment
 * groups.
 *
 * Exported for testing.
 *
 * @param experimentOverridesQuery The value of the "experiment_overrides"
 *   query parameter.
 *   (e.g. "12345678-1234-1234-1234-123456789012=treatment,uuid2=control")
 */
export function parseExperimentOverrides(
  experimentOverridesQuery: string | undefined,
): ExperimentOverrideMapping {
  if (!experimentOverridesQuery) {
    return {};
  }
  const mobileWebUUIDs = Enum.values(ExperimentUUIDs).map(uuid =>
    uuid.toLowerCase(),
  );
  const mobileWebGroups = Enum.values(ExperimentGroups).map(group =>
    group.toLowerCase(),
  );

  return experimentOverridesQuery
    .split(',')
    .map(exp => {
      const [uuid, group] = exp.split('=');
      return { uuid, group };
    })
    .filter(
      override =>
        mobileWebUUIDs.includes(override.uuid.toLowerCase()) &&
        mobileWebGroups.includes(override.group.toLowerCase()),
    )
    .reduce(
      (prev, cur) => {
        prev[
          Enum.getValueFromString(ExperimentUUIDs, cur.uuid)
        ] = Enum.getValueFromString(ExperimentGroups, cur.group);
        return prev;
      },
      {} as ExperimentOverrideMapping,
    );
}
