import type { MergeFunc } from '@assets/filters/common/state-parsers/mergeConfigs';

export const mergeProducersConfig: MergeFunc<'producers'> = (
   oldState,
   newState,
   { producerIds: selected = [] },
   { topSellingBucketsSize = Number.POSITIVE_INFINITY },
) => {
   if (!oldState?.values.length) {
      return oldState;
   }

   // Merge normally if:
   // - new state is empty
   // - the producers filter is currently in use (do not change the order)
   // - order by on filter values is not supported / disabled;
   //       or the order should not change - ordered alphabetically if <= topSellingBucketsSize
   if (!newState
      || (selected.length > 0)
      || (!oldState.values_count || oldState.values_count <= topSellingBucketsSize)
   ) {
      return {
         ...oldState,
         values: oldState.values.map(producer => {
            const newProducer = newState?.values.find(u => u.id === producer.id);

            return {
               ...producer,
               count: newProducer?.count ?? 0,
            };
         }),
      };
   }

   // Use the updated values -> ordered by top-selling products
   // in the filtered section.

   return {
      ...oldState,
      values: newState.values,
   };
};
