import Router from 'next/router';
import { ofType } from 'redux-observable';
import { filter, tap } from 'rxjs/operators';

import queue from '../helpers/queue';
import { addQueriesAction } from '../slices';
import { isEqual } from '@/modules/@common/helpers';

export default (action$) =>
  action$.pipe(
    ofType(addQueriesAction.type),
    filter((action) => {
      const addQueries = action.payload;
      const prevQueries = Router.query;

      return !isEqual(prevQueries, addQueries);
    }),
    tap((action) => {
      const addQueries = action.payload;

      queue.items.push({
        pathname: Router.pathname,
        getQuery: (routerQuery) => ({ ...routerQuery, ...addQueries }),
      });

      if (!queue.isInProcessing) {
        queue.runProcessing();
      }
    }),
    filter(() => false),
  );
