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

import queue from '../helpers/queue';
import { removeQueriesAction } from '../slices';

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

      if (typeof key === 'string') {
        return key && prevQueries[key];
      }

      return true;
    }),
    tap((action) => {
      const removeQueries = action.payload;

      if (typeof removeQueries === 'string') {
        queue.items.push({
          pathname: Router.pathname,
          getQuery: (routerQuery) => {
            const { [removeQueries]: omit, ...newQueries } = routerQuery;
            return newQueries;
          },
        });
      }

      if (Array.isArray(removeQueries)) {
        queue.items.push({
          pathname: Router.pathname,
          getQuery: (routerQuery) =>
            Object.keys(routerQuery).reduce(
              (acc, cur) =>
                removeQueries.includes(cur)
                  ? acc
                  : {
                      ...acc,
                      [cur]: routerQuery[cur],
                    },
              {},
            ),
        });
      }

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