import { ArrayValue, NumberValue, Schema, SchemaValidationError, Value, } from '@coveo/bueno';
import { requiredNonEmptyString } from '../../utils/validate-payload.js';
export const templateSchema = new Schema({
    content: new Value({ required: true }),
    conditions: new Value({ required: true }),
    priority: new NumberValue({ required: false, default: 0, min: 0 }),
    fields: new ArrayValue({
        required: false,
        each: requiredNonEmptyString,
    }),
});
export function buildTemplatesManager() {
    const templates = [];
    const validateTemplate = (template) => {
        const validated = templateSchema.validate(template);
        const areConditionsValid = template.conditions.every((condition) => condition instanceof Function);
        if (!areConditionsValid) {
            throw new SchemaValidationError('Each template condition should be a function that takes a Result or Product as an argument and returns a boolean');
        }
        return validated;
    };
    return {
        registerTemplates(...newTemplates) {
            newTemplates.forEach((template) => {
                const templatesWithDefault = {
                    ...validateTemplate(template),
                    fields: template.fields || [],
                };
                templates.push(templatesWithDefault);
            });
            templates.sort((a, b) => b.priority - a.priority);
        },
        selectTemplate(item) {
            const template = templates.find((template) => template.conditions.every((condition) => condition(item)));
            return template ? template.content : null;
        },
        selectLinkTemplate(item) {
            const template = templates.find((template) => template.conditions.every((condition) => condition(item)));
            return template ? template.linkContent : null;
        },
    };
}
