import { Facet } from '@akinon/next/types';
import { Middleware, UnknownAction } from '@reduxjs/toolkit';
import { setSelectedFacets } from '@theme/redux/reducers/category';

const getSelectedFacets = (facets: Array<Facet>) => {
  return facets
    ?.map((facet) => {
      return {
        ...facet,
        data: {
          ...facet.data,
          choices: facet.data.choices.filter((choice) => choice.is_selected)
        }
      };
    })
    .filter((facet) => {
      return facet.data.choices.filter((choice) => choice.is_selected).length;
    });
};

const categoryMiddleware: Middleware = ({ dispatch, getState }) => {
  return (next) => (action) => {
    const result = next(action);
    const act = action as UnknownAction;

    if (act.type === 'category/setFacets') {
      const facets: Array<Facet> = (result as { payload: Array<Facet> }).payload;
      const selectedFacets = getSelectedFacets(facets);

      dispatch(setSelectedFacets(selectedFacets));
    } else if (act.type === 'category/toggleFacet') {
      const selectedFacets = getSelectedFacets(
        getState().category.selectedFacets
      );

      dispatch(setSelectedFacets(selectedFacets));
    }

    return result;
  };
};

export default categoryMiddleware;
