import { combineReducers } from 'redux';

import { Action } from 'mweb/common/actions/root';
import {
  EXPERIMENTS_CONFIGURED_ACTION_TYPE,
  EXPERIMENTS_RECORD_DECISION_ACTION_TYPE,
  ExperimentNames,
  ExperimentGroups,
  ActiveExperimentData,
} from 'mweb/common/actions/experiments';

export interface ExperimentsState {
  readonly activeExperiments: ActiveExperimentsState;
  readonly recordedDecisions: ExperimentDecisionMap;
}

export type ActiveExperimentsState = Readonly<
  Partial<Record<ExperimentNames, ActiveExperimentData>>
>;

export interface ExperimentDecisionMap {
  readonly [experimentName: string]: ExperimentGroups;
}

function activeExperiments(
  state: ActiveExperimentsState = {},
  action: Action,
): ActiveExperimentsState {
  switch (action.type) {
    case EXPERIMENTS_CONFIGURED_ACTION_TYPE:
      return {
        ...state,
        [action.payload.name]: action.payload,
      };
    default:
      return state;
  }
}

function recordedDecisions(
  state: ExperimentDecisionMap = {},
  action: Action,
): ExperimentDecisionMap {
  switch (action.type) {
    case EXPERIMENTS_RECORD_DECISION_ACTION_TYPE:
      return {
        ...state,
        [action.payload.name]: action.payload.group,
      };
    default:
      return state;
  }
}

export function buildExperimentsReducer(): (
  state: ExperimentsState | undefined,
  action: Action,
) => ExperimentsState {
  return combineReducers<ExperimentsState>({
    activeExperiments,
    recordedDecisions,
  });
}
