import { buildFilterableCommerceAPIRequest } from '../../../common/filterable-commerce-api-request-builder.js';
import { getFacetIdWithoutCommerceFieldSuggestionNamespace } from '../commerce-facet-search-actions.js';
export const buildCategoryFacetSearchRequest = (facetId, state, isFieldSuggestionsRequest, navigatorContext) => {
    const baseFacetQuery = state.categoryFacetSearchSet[facetId].options.query;
    const facetQuery = `*${baseFacetQuery}*`;
    const categoryFacet = state.commerceFacetSet[getFacetIdWithoutCommerceFieldSuggestionNamespace(facetId)]?.request;
    const path = categoryFacet && isCategoryFacetRequest(categoryFacet)
        ? categoryFacet && getPathToSelectedCategoryFacetItem(categoryFacet)
        : [];
    const ignorePaths = path.length ? [path] : [];
    const query = isFieldSuggestionsRequest
        ? baseFacetQuery
        : state.commerceQuery?.query;
    const { url, accessToken, organizationId, trackingId, language, country, currency, clientId, context, ...restOfCommerceAPIRequest } = buildFilterableCommerceAPIRequest(state, navigatorContext);
    return {
        url,
        accessToken,
        organizationId,
        facetId: getFacetIdWithoutCommerceFieldSuggestionNamespace(facetId),
        facetQuery: isFieldSuggestionsRequest ? '*' : facetQuery,
        ignorePaths,
        trackingId,
        language,
        country,
        currency,
        clientId,
        context,
        query,
        ...(!isFieldSuggestionsRequest && { ...restOfCommerceAPIRequest }),
    };
};
function isCategoryFacetRequest(request) {
    return request.type === 'hierarchical';
}
const getPathToSelectedCategoryFacetItem = (categoryFacet) => {
    const path = [];
    let selectedValue = categoryFacet.values[0];
    while (selectedValue) {
        path.push(selectedValue.value);
        selectedValue = selectedValue.children[0];
    }
    return path;
};
