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

import { DEMAND_TAG_FREQUENCY_TAB_STATUS } from '@/modules/marketplace/account/constants';

import * as selectors from '../selectors';
import { getFrequencyCapTabAction, setFrequencyCapTabAction } from '../slices';

export default (action$, state$) =>
  action$.pipe(
    ofType(getFrequencyCapTabAction.type),
    switchMap(() => {
      let setFrequencyCap = {};
      const state = state$.value;

      const info = selectors.infoSelector(state);
      const pageConfig = selectors.pageConfigSelector(state);

      if (
        info &&
        info.frequency &&
        info.frequency.status &&
        info.frequency.type &&
        info.frequency.value &&
        info.frequency.timeframe &&
        info.frequency.amount
      ) {
        setFrequencyCap = {
          ...info.frequency,
          prevSavedData: null,
        };
      } else if (!pageConfig?.isCreatingNew) {
        setFrequencyCap = {
          status: DEMAND_TAG_FREQUENCY_TAB_STATUS.disabled,
        };
      }

      return concat(of(setFrequencyCapTabAction(setFrequencyCap)));
    }),
  );
