import { createAsyncThunk, } from '@reduxjs/toolkit';
import { requiredNonEmptyString } from '../../../../utils/validate-payload.js';
import { buildCategoryFacetSearchRequest } from './category/commerce-category-facet-search-request-builder.js';
import { buildFacetSearchRequest } from './regular/commerce-regular-facet-search-request-builder.js';
const getExecuteFacetSearchThunkPayloadCreator = (isFieldSuggestionsRequest) => async ({ facetId, facetSearchType }, { getState, extra: { validatePayload, navigatorContext, apiClient } }) => {
    const state = getState();
    validatePayload(facetId, requiredNonEmptyString);
    const req = isRegularFacetSearchState(state, facetId) ||
        isRegularFieldSuggestionsState(state, facetId)
        ? buildFacetSearchRequest(facetId, state, isFieldSuggestionsRequest, navigatorContext)
        : buildCategoryFacetSearchRequest(facetId, state, isFieldSuggestionsRequest, navigatorContext);
    const response = await apiClient.facetSearch(req, facetSearchType);
    return { facetId, response };
};
export const executeCommerceFacetSearch = createAsyncThunk('commerce/facetSearch/executeSearch', getExecuteFacetSearchThunkPayloadCreator(false));
export const executeCommerceFieldSuggest = createAsyncThunk('commerce/facetSearch/facetFieldSuggest', getExecuteFacetSearchThunkPayloadCreator(true));
export const isRegularFacetSearchState = (s, facetId) => {
    return ('facetSearchSet' in s &&
        s.facetSearchSet[facetId] !== undefined &&
        s.commerceFacetSet[facetId] !== undefined);
};
export const isRegularFieldSuggestionsState = (s, facetId) => {
    if (!('fieldSuggestionsOrder' in s)) {
        return false;
    }
    return s.fieldSuggestionsOrder.some((facet) => facet.facetId === facetId && facet.type === 'regular');
};
const commerceFieldSuggestionNamespace = 'field_suggestion:';
export function getFacetIdWithoutCommerceFieldSuggestionNamespace(facetId) {
    return facetId.startsWith(commerceFieldSuggestionNamespace)
        ? facetId.slice(commerceFieldSuggestionNamespace.length)
        : facetId;
}
export function getFacetIdWithCommerceFieldSuggestionNamespace(facetId) {
    return facetId.startsWith(commerceFieldSuggestionNamespace)
        ? facetId
        : `${commerceFieldSuggestionNamespace}${facetId}`;
}
