import { MultipleRecommendationError } from '../../../../utils/errors.js';
import { recommendationInternalOptionKey, } from '../../types/common.js';
export function filterRecommendationControllers(controllers, controllerDefinitions) {
    const slotIdSet = new Set();
    const isRecommendationDefinition = (controllerDefinition) => {
        const isControllerRecommendation = 'recommendation' in controllerDefinition &&
            controllerDefinition.recommendation === true;
        const hasSlotId = recommendationInternalOptionKey in controllerDefinition &&
            'slotId' in
                controllerDefinition[recommendationInternalOptionKey];
        return isControllerRecommendation && hasSlotId;
    };
    const ensureSingleRecommendationPerSlot = (slotId) => {
        throw new MultipleRecommendationError(slotId);
    };
    const filtered = Object.entries(controllerDefinitions).filter(([_, value]) => {
        if (!isRecommendationDefinition(value)) {
            return false;
        }
        const { slotId } = value[recommendationInternalOptionKey];
        const key = slotId;
        if (slotIdSet.has(slotId)) {
            ensureSingleRecommendationPerSlot(slotId);
            return false;
        }
        slotIdSet.add(key);
        return true;
    });
    const name = filtered.map(([name, _]) => name);
    return {
        /**
         * Go through all the controllers passed in argument and only refresh recommendation controllers.
         *
         * @param controllers - A record of all controllers where the key is the controller name and the value is the controller instance.
         * @param controllerNames - A list of all recommendation controllers to refresh
         */
        refresh(whitelist) {
            if (whitelist === undefined) {
                return;
            }
            const isRecommendationController = (key) => name.includes(key) && whitelist.includes(key);
            for (const [key, controller] of Object.entries(controllers)) {
                if (isRecommendationController(key)) {
                    controller.refresh?.();
                }
            }
        },
    };
}
