import { defaultFacetSearchOptions, handleFacetSearchRegistration, } from '../../../facets/facet-search-set/facet-search-reducer-helpers.js';
import { getFacetIdWithCommerceFieldSuggestionNamespace } from './commerce-facet-search-actions.js';
export function handleCommerceFacetSearchFulfilled(state, payload, requestId) {
    const { facetId, response } = payload;
    const search = state[facetId];
    if (!search) {
        return;
    }
    if (search.requestId !== requestId) {
        return;
    }
    search.isLoading = false;
    if ('success' in response) {
        search.response = response.success;
    }
}
export function handleCommerceFacetFieldSuggestionsFulfilled(state, payload, requestId, buildEmptyResponse) {
    const { facetId, response } = payload;
    const namespacedFacetId = getFacetIdWithCommerceFieldSuggestionNamespace(facetId);
    let search = state[namespacedFacetId];
    if (!search) {
        handleFacetSearchRegistration(state, { facetId: namespacedFacetId }, buildEmptyResponse);
        search = state[namespacedFacetId];
    }
    else if (search.requestId !== requestId) {
        return;
    }
    search.isLoading = false;
    if ('success' in response) {
        search.response = response.success;
    }
}
export function handleCommerceFetchQuerySuggestionsFulfilledForRegularFacet(state, payload, requestId, buildEmptyResponse) {
    if (!payload.fieldSuggestionsFacets) {
        return;
    }
    for (const fieldSuggestionFacet of payload.fieldSuggestionsFacets) {
        if (fieldSuggestionFacet.facetId in state ||
            fieldSuggestionFacet.type !== 'regular') {
            continue;
        }
        state[fieldSuggestionFacet.facetId] = {
            options: {
                ...defaultFacetSearchOptions,
                query: payload.query ?? '',
            },
            isLoading: false,
            response: buildEmptyResponse(),
            initialNumberOfValues: defaultFacetSearchOptions.numberOfValues,
            requestId,
        };
    }
}
export function handleCommerceFetchQuerySuggestionsFulfilledForCategoryFacet(state, payload, requestId, buildEmptyResponse) {
    if (!payload.fieldSuggestionsFacets) {
        return;
    }
    for (const fieldSuggestionFacet of payload.fieldSuggestionsFacets) {
        const namespacedFacetId = getFacetIdWithCommerceFieldSuggestionNamespace(fieldSuggestionFacet.facetId);
        if (namespacedFacetId in state ||
            fieldSuggestionFacet.type !== 'hierarchical') {
            continue;
        }
        state[namespacedFacetId] = {
            options: {
                ...defaultFacetSearchOptions,
                query: payload.query ?? '',
            },
            isLoading: false,
            response: buildEmptyResponse(),
            initialNumberOfValues: defaultFacetSearchOptions.numberOfValues,
            requestId,
        };
    }
}
