import { isNullOrUndefined } from '@coveo/bueno';
import { createSelector } from '@reduxjs/toolkit';
import { stateKey } from '../../../app/state-key.js';
import { getQ } from '../../parameter-manager/parameter-manager-selectors.js';
import { totalEntriesPrincipalSelector } from '../pagination/pagination-selectors.js';
import { activeParametersSelector as coreActiveParametersSelector } from '../parameters/parameters-selectors.js';
import { getCommerceQueryInitialState } from '../query/query-state.js';
/**
 * Duplicate selector since the state is no longer accessible externally
 * TODO: KIT-3199: Update all other selectors to use the engine as a parameter
 */
export const responseIdSelectorFromEngine = (engine) => engine[stateKey].commerceSearch.responseId;
export const responseIdSelector = (state) => state.commerceSearch.responseId;
export const requestIdSelector = (state) => state.commerceSearch.requestId;
export const numberOfProductsSelector = (state) => state.commerceSearch?.results.length ||
    state.commerceSearch?.products.length ||
    0;
export const moreProductsAvailableSelector = createSelector((state) => ({
    total: totalEntriesPrincipalSelector(state),
    current: numberOfProductsSelector(state),
}), ({ current, total }) => current < total);
export const isLoadingSelector = (state) => {
    const isLoading = state.commerceSearch?.isLoading;
    return isNullOrUndefined(isLoading) ? false : isLoading;
};
export const errorSelector = (state) => state.commerceSearch?.error ?? null;
export const querySelector = (state) => state.commerceQuery?.query ?? '';
const queryExecutedSelector = (state) => state.commerceSearch?.queryExecuted;
export const queryExecutedFromResponseSelector = (state, response) => {
    if (!isNullOrUndefined(response.queryCorrection?.correctedQuery)) {
        return response.queryCorrection.correctedQuery;
    }
    return querySelector(state);
};
export const activeParametersSelector = (state) => {
    return {
        ...getQ(state?.commerceQuery, (s) => s.query, getCommerceQueryInitialState().query),
        ...coreActiveParametersSelector(state),
    };
};
export function enrichedSummarySelector(state) {
    return {
        query: queryExecutedSelector(state) || '',
    };
}
