import { buildCommerceEngine, } from '../../../app/commerce-engine/commerce-engine.js';
import { buildLogger } from '../../../app/logger.js';
import { stateKey } from '../../../app/state-key.js';
import { createWaitForActionMiddleware, createWaitForActionMiddlewareForRecommendation, } from '../../../utils/utils.js';
import { buildControllerDefinitions } from '../controller-utils.js';
import { SolutionType } from '../types/controller-constants.js';
function isListingFetchCompletedAction(action) {
    return /^commerce\/productListing\/fetch\/(fulfilled|rejected)$/.test(action.type);
}
function isSearchCompletedAction(action) {
    return /^commerce\/search\/executeSearch\/(fulfilled|rejected)$/.test(action.type);
}
function isRecommendationCompletedAction(action) {
    return /^commerce\/recommendations\/fetch\/(fulfilled|rejected)$/.test(action.type);
}
function noSearchActionRequired(_action) {
    return true;
}
function buildSSRCommerceEngine(solutionType, options, recommendationCount) {
    let actionCompletionMiddleware;
    const middlewares = [];
    const memo = new Set();
    switch (solutionType) {
        case SolutionType.listing:
            actionCompletionMiddleware = createWaitForActionMiddleware(isListingFetchCompletedAction);
            middlewares.push(actionCompletionMiddleware);
            break;
        case SolutionType.search:
            actionCompletionMiddleware = createWaitForActionMiddleware(isSearchCompletedAction);
            middlewares.push(actionCompletionMiddleware);
            break;
        case SolutionType.recommendation:
            middlewares.push(...Array.from({ length: recommendationCount }, () => createWaitForActionMiddlewareForRecommendation(isRecommendationCompletedAction, memo)));
            break;
        case SolutionType.standalone:
            actionCompletionMiddleware = createWaitForActionMiddleware(noSearchActionRequired);
            break;
        default:
            throw new Error('Unsupported solution type', solutionType);
    }
    const commerceEngine = buildCommerceEngine({
        ...options,
        middlewares: [
            ...(options.middlewares ?? []),
            ...middlewares.map(({ middleware }) => middleware),
        ],
    });
    return {
        ...commerceEngine,
        get [stateKey]() {
            return commerceEngine[stateKey];
        },
        waitForRequestCompletedAction() {
            return [...middlewares.map(({ promise }) => promise)];
        },
    };
}
function fetchActiveRecommendationControllers(controllerProps, solutionType) {
    return solutionType === SolutionType.recommendation
        ? Object.values(controllerProps).filter((controller) => controller &&
            typeof controller === 'object' &&
            'enabled' in controller &&
            controller.enabled).length
        : 0;
}
export const buildFactory = (controllerDefinitions, options) => (solutionType) => async (...[buildOptions]) => {
    const logger = buildLogger(options.loggerOptions);
    if (!options.navigatorContextProvider) {
        logger.warn('[WARNING] Missing navigator context in server-side code. Make sure to set it with `setNavigatorContextProvider` before calling fetchStaticState()');
    }
    const controllerProps = buildOptions && 'controllers' in buildOptions
        ? buildOptions.controllers
        : {};
    const enabledRecommendationControllers = fetchActiveRecommendationControllers(controllerProps, solutionType);
    const engine = buildSSRCommerceEngine(solutionType, buildOptions && 'extend' in buildOptions && buildOptions?.extend
        ? await buildOptions.extend(options)
        : options, enabledRecommendationControllers);
    const controllers = buildControllerDefinitions({
        definitionsMap: (controllerDefinitions ?? {}),
        engine,
        solutionType,
        propsMap: (buildOptions && 'controllers' in buildOptions
            ? buildOptions.controllers
            : {}),
    });
    return {
        engine,
        controllers,
    };
};
