import { ofType } from 'redux-observable';
import { concat, of } from 'rxjs';
import { switchMap } from 'rxjs/operators';

import { modelsByProviders } from '../../helpers';
import { getAllAnalyticsModelsComputedSelector } from '../selectors';
import { onChangeModelFormAction, updateConfigurationByPropAction } from '../slices';

export default (action$, state$) =>
  action$.pipe(
    ofType(onChangeModelFormAction.type),
    switchMap(({ payload: { providerName, fieldName, formId, value } }) => {
      const providerModelName = modelsByProviders[providerName];
      const model = getAllAnalyticsModelsComputedSelector(state$.value)[providerModelName];

      const updatedFormList = {
        ...model,
        formList: model.formList.map((form) => {
          const updatedForm = { ...form };

          if (form.formId === formId) {
            updatedForm[fieldName] = value;
          }

          return updatedForm;
        }),
      };

      return concat(
        of(
          updateConfigurationByPropAction({
            [providerModelName]: updatedFormList,
          }),
        ),
      );
    }),
  );
