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 = createSelector((engine) => engine[stateKey].commerceSearch.responseId, (responseId) => responseId);
export const responseIdSelector = createSelector((state) => state.commerceSearch.responseId, (responseId) => responseId);
export const requestIdSelector = createSelector((state) => state.commerceSearch.requestId, (requestId) => requestId);
export const numberOfProductsSelector = createSelector((state) => state.commerceSearch?.products.length || 0, (len) => len);
export const moreProductsAvailableSelector = createSelector((state) => ({
    total: totalEntriesPrincipalSelector(state),
    current: numberOfProductsSelector(state),
}), ({ current, total }) => current < total);
export const isLoadingSelector = createSelector((state) => state.commerceSearch?.isLoading, (isLoading) => (isNullOrUndefined(isLoading) ? false : isLoading));
export const errorSelector = createSelector((state) => state.commerceSearch?.error, (error) => error ?? null);
export const querySelector = createSelector((state) => state.commerceQuery?.query, (query) => query ?? '');
const queryExecutedSelector = createSelector((state) => state.commerceSearch?.queryExecuted, (query) => query);
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) || '',
    };
}
