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

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

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

      const updatedFormList = {
        ...model,
        formList: model.formList.filter((form) => form.formId !== formId),
      };

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