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

import { searchFiltersSelector } from '../selectors';
import { addFiltersQueriesAction, restartSearchEventAction } from '../slices';
import { isEqual } from '@/modules/@common/helpers';
import { configSelector } from '@/modules/editorial/editorialSearchFilter/filterContainer/redux/selectors';
import { configChangedEventAction } from '@/modules/editorial/editorialSearchFilter/filterContainer/redux/slices';

export default (action$, state$) =>
  action$.pipe(
    ofType(configChangedEventAction.type),
    switchMap(() => {
      const state = state$.value;
      const searchFilters = searchFiltersSelector(state);
      const config = configSelector(state);

      const actions = [];

      if (!isEqual(config, searchFilters)) {
        actions.push(of(restartSearchEventAction()));
      }

      if (searchFilters) {
        actions.push(of(addFiltersQueriesAction()));
      }

      return concat(...actions);
    }),
  );
