import { buildProductListing } from '../../../controllers/commerce/product-listing/headless-product-listing.js';
import { buildSearch } from '../../../controllers/commerce/search/headless-search.js';
import { createStaticState } from '../controller-utils.js';
import { SolutionType } from '../types/controller-constants.js';
import { buildFactory } from './build-factory.js';
function findAndExecuteMethod(controllers, methodName) {
    for (const controller of Object.values(controllers)) {
        if (typeof Object.getOwnPropertyDescriptor(controller, methodName)?.value ===
            'function') {
            controller[methodName]();
            return true;
        }
    }
    return false;
}
function executeFirstRequestForListing(controllers, engine) {
    const controllerExecuted = findAndExecuteMethod(controllers, 'executeFirstRequest');
    if (!controllerExecuted) {
        buildProductListing(engine).executeFirstRequest();
    }
}
function executeFirstRequestForSearch(controllers, engine) {
    const controllerExecuted = findAndExecuteMethod(controllers, 'executeFirstSearch');
    if (!controllerExecuted) {
        buildSearch(engine).executeFirstSearch();
    }
}
export function fetchStaticStateFactory(controllerDefinitions, options) {
    return (solutionType) => async (params) => {
        const solutionTypeBuild = buildFactory(controllerDefinitions, options)(solutionType);
        const { engine, controllers } = await solutionTypeBuild(params);
        switch (solutionType) {
            case SolutionType.listing:
                executeFirstRequestForListing(controllers, engine);
                break;
            case SolutionType.search:
                executeFirstRequestForSearch(controllers, engine);
                break;
        }
        const searchActions = await Promise.all(engine.waitForRequestCompletedAction());
        const staticState = createStaticState({
            searchActions,
            controllers,
        });
        const { controllers: controllerProps, ...restParams } = params;
        return {
            ...restParams,
            ...staticState,
            ...(controllerProps && { controllerProps }),
        };
    };
}
