import { RecordValue, Schema } from '@coveo/bueno';
import { isFacetVisibleOnTab } from '../../../features/facet-options/facet-options-utils.js';
import { findActiveValueAncestry } from '../../../features/facets/category-facet-set/category-facet-utils.js';
import { getFacets, getQ, getSortCriteria, getTab, } from '../../../features/parameter-manager/parameter-manager-selectors.js';
import { getQueryInitialState } from '../../../features/query/query-state.js';
import { restoreSearchParameters, } from '../../../features/search-parameters/search-parameter-actions.js';
import { searchParametersDefinition } from '../../../features/search-parameters/search-parameter-schema.js';
import { initialSearchParameterSelector } from '../../../features/search-parameters/search-parameter-selectors.js';
import { getSortCriteriaInitialState } from '../../../features/sort-criteria/sort-criteria-state.js';
import { validateInitialState } from '../../../utils/validate-payload.js';
import { buildController, } from '../../controller/headless-controller.js';
const initialStateSchema = new Schema({
    parameters: new RecordValue({
        options: { required: true },
        values: searchParametersDefinition,
    }),
});
/**
 * Creates a `SearchParameterManager` controller instance.
 *
 * @param engine - The headless engine.
 * @param props - The configurable `SearchParameterManager` properties.
 * @returns A `SearchParameterManager` controller instance.
 */
export function buildCoreSearchParameterManager(engine, props) {
    const { dispatch } = engine;
    const controller = buildController(engine);
    validateInitialState(engine, initialStateSchema, props.initialState, 'buildSearchParameterManager');
    const parametersWithValidTab = ensureTabIsValid(engine.state.tabSet, props.initialState.parameters);
    dispatch(restoreSearchParameters(parametersWithValidTab));
    return {
        ...controller,
        synchronize(parameters) {
            const enrichedParametersWithValidTab = ensureTabIsValid(engine.state.tabSet, enrichParameters(engine, parameters));
            dispatch(restoreSearchParameters(enrichedParametersWithValidTab));
        },
        get state() {
            const parameters = getCoreActiveSearchParameters(engine);
            return { parameters };
        },
    };
}
export function enrichParameters(engine, parameters) {
    return {
        ...initialSearchParameterSelector(engine.state),
        ...parameters,
    };
}
/**
 * This function is essential to ensure that the `tab` parameter is valid.
 * We need it to be valid prior to dispatching the `restoreSearchParameters` action since the facet logic relies on the `tab` parameter to determine which facets to show.
 * If the `tab` parameter is invalid, it can lead to unexpected behavior in the facets.
 */
function ensureTabIsValid(tabSet, parameters) {
    if (parameters.tab && tabSet) {
        const tabExists = Object.values(tabSet).some((tab) => tab.id === parameters.tab);
        const currentActiveTab = Object.values(tabSet).find((tab) => tab.isActive);
        if (!tabExists && currentActiveTab) {
            return { ...parameters, tab: currentActiveTab.id };
        }
        else if (!tabExists) {
            return { ...parameters, tab: '' };
        }
    }
    return parameters;
}
export function getCoreActiveSearchParameters(engine) {
    const state = engine.state;
    return {
        ...getQ(state.query, (s) => s.q, getQueryInitialState().q),
        ...getTab(state.tabSet, (tabSet) => {
            const activeTab = Object.values(tabSet ?? {}).find((tab) => tab.isActive);
            return activeTab ? activeTab.id : Object.keys(tabSet ?? {})[0];
        }, state.tabSet ? Object.keys(state.tabSet)[0] : ''),
        ...getSortCriteria(state.sortCriteria, (sortCriteria) => sortCriteria, getSortCriteriaInitialState()),
        ...getRegularFacetParams(state),
        ...getCategoryFacets(state),
        ...getNumericFacets(state),
        ...getDateFacets(state),
        ...getAutomaticFacets(state),
    };
}
function getActiveTab(state) {
    const tabSet = state.tabSet;
    if (!tabSet) {
        return undefined;
    }
    const activeTab = Object.values(tabSet).find((tab) => tab.isActive);
    return activeTab?.id;
}
function facetIsEnabledAndVisibleOnTab(state) {
    const activeTab = getActiveTab(state);
    return (facetId) => {
        const facetOptions = state.facetOptions?.facets[facetId];
        const isEnabled = facetOptions?.enabled ?? true;
        const isVisibleOnTab = isFacetVisibleOnTab(facetOptions?.tabs, activeTab);
        return isEnabled && isVisibleOnTab;
    };
}
function getSelectedRangeValues(request) {
    return request.currentValues.filter((fv) => fv.state === 'selected');
}
function getRegularFacetParams(state) {
    const section = state.facetSet;
    if (section === undefined) {
        return {};
    }
    const isEnabled = facetIsEnabledAndVisibleOnTab(state);
    const f = {};
    const fExcluded = {};
    for (const [facetId, { request }] of Object.entries(section)) {
        if (!isEnabled(facetId)) {
            continue;
        }
        const selectedValues = request.currentValues
            .filter((fv) => fv.state === 'selected')
            .map((fv) => fv.value);
        const excludedValues = request.currentValues
            .filter((fv) => fv.state === 'excluded')
            .map((fv) => fv.value);
        if (selectedValues.length) {
            f[facetId] = selectedValues;
        }
        if (excludedValues.length) {
            fExcluded[facetId] = excludedValues;
        }
    }
    return {
        ...(Object.keys(f).length ? { f } : {}),
        ...(Object.keys(fExcluded).length ? { fExcluded } : {}),
    };
}
function getCategoryFacets(state) {
    return getFacets(state.categoryFacetSet, facetIsEnabledAndVisibleOnTab(state), (request) => findActiveValueAncestry(request.currentValues).map((v) => v.value), 'cf');
}
function getNumericFacets(state) {
    return getFacets(state.numericFacetSet, facetIsEnabledAndVisibleOnTab(state), getSelectedRangeValues, 'nf');
}
function getDateFacets(state) {
    return getFacets(state.dateFacetSet, facetIsEnabledAndVisibleOnTab(state), getSelectedRangeValues, 'df');
}
function getAutomaticFacets(state) {
    const set = state.automaticFacetSet?.set;
    if (set === undefined) {
        return {};
    }
    const af = Object.entries(set)
        .map(([facetId, { response }]) => {
        const selectedValues = getSelectedResponseValues(response);
        return selectedValues.length ? { [facetId]: selectedValues } : {};
    })
        // biome-ignore lint/performance/noAccumulatingSpread: <>
        .reduce((acc, obj) => ({ ...acc, ...obj }), {});
    return Object.keys(af).length ? { af } : {};
}
function getSelectedResponseValues(response) {
    return response.values
        .filter((fv) => fv.state === 'selected')
        .map((fv) => fv.value);
}
