import { filterObject } from '../../../utils/utils.js';
import { composeFunction } from '../../ssr-engine/common.js';
import { createStaticState } from '../common.js';
import { SolutionType, } from '../types/common.js';
import { buildFactory, } from './build-factory.js';
import { filterRecommendationControllers } from './utils/recommendation-filter.js';
export function fetchRecommendationStaticStateFactory(controllerDefinitions, options) {
    const getAllowedRecommendationKeys = (props) => {
        if (props && 'controllers' in props) {
            const enabledRecommendationControllers = filterObject(props.controllers, (value) => Boolean(value.enabled));
            return Object.keys(enabledRecommendationControllers);
        }
        return [];
    };
    return composeFunction(async (...params) => {
        const [props] = params;
        const allowedRecommendationKeys = getAllowedRecommendationKeys(props);
        const solutionTypeBuild = await buildFactory(controllerDefinitions, options)(SolutionType.recommendation);
        const buildResult = (await solutionTypeBuild(...params));
        const staticState = await fetchRecommendationStaticStateFactory(controllerDefinitions, options).fromBuildResult({
            buildResult,
            allowedRecommendationKeys,
        });
        return staticState;
    }, {
        fromBuildResult: async (...params) => {
            const [{ buildResult: { engine, controllers }, allowedRecommendationKeys, },] = params;
            filterRecommendationControllers(controllers, controllerDefinitions ?? {}).refresh(allowedRecommendationKeys);
            const searchActions = await Promise.all(engine.waitForRequestCompletedAction());
            return createStaticState({
                searchActions,
                controllers,
            });
        },
    });
}
