import type { FilterParams } from '@assets/filters/common/state-parsers/filterParams';
import type { IGraphQLBaseFilterInput } from '@assets/interfaces/gqlApi/graphql';
import { Logger } from '@assets/filters/common/utils/logger';

export type BaseFilter = IGraphQLBaseFilterInput;

const logger = new Logger('baseFilter');

export function parseBaseFilter(baseFilterParams: FilterParams) {
   const baseFilter: BaseFilter = {};

   if (baseFilterParams.sectionIds?.length) {
      baseFilter.categoryId = +baseFilterParams.sectionIds[0];
   } else if (baseFilterParams.sectionIdsFilter?.length) {
      baseFilter.categoryId = +baseFilterParams.sectionIdsFilter[0];
   }

   if (baseFilterParams.producers?.length) {
      baseFilter.producerId = +baseFilterParams.producers[0];
   } else if (baseFilterParams.parameters?.length) {
      const firstParameter = baseFilterParams.parameters
         .find(p => p.type === 'list') as unknown as { value: (number | string)[], type: 'list' };

      if (firstParameter?.value.length) {
         baseFilter.parameterValueId = +firstParameter.value[0];
      }
   }

   if (baseFilter.categoryId === -1 && baseFilterParams.search) {
      baseFilter.search = baseFilterParams.search;
   }

   if (!Object.keys(baseFilter).length) {
      logger.warn('Invalid base filter', baseFilterParams);
   }

   return baseFilter;
}
