/**
 * Standalone collection validation functions extracted from validationUtils.js.
 */

function validateArray(configValue, rules, fieldSchema, name, key, logger) {
    if (!Array.isArray(configValue)) {
        logger.info(`${name}.${key} is not an array. Using default value.`);
        return fieldSchema.default;
    }
    const validatedArray = configValue
        .filter((item) => {
            switch (rules.itemType) {
                case "number": return typeof item === "number";
                case "string": return typeof item === "string";
                case "null": return true;
                default: return typeof item === rules.itemType;
            }
        })
        .slice(0, rules.maxLength || Infinity);
    if (validatedArray.length < (rules.minLength ?? 1)) {
        logger.warn(
            `${name}.${key} contains fewer items than allowed (${rules.minLength}). Using default value.`
        );
        return fieldSchema.default;
    }
    return validatedArray;
}

function validateSet(configValue, rules, fieldSchema, name, key, logger) {
    if (!(configValue instanceof Set)) {
        logger.info(`${name}.${key} is not a Set. Converting to one using default value.`);
        return new Set(fieldSchema.default);
    }
    const validatedArray = [...configValue]
        .filter((item) => {
            switch (rules.itemType) {
                case "number": return typeof item === "number";
                case "string": return typeof item === "string";
                case "null": return true;
                default: return typeof item === rules.itemType;
            }
        })
        .slice(0, rules.maxLength || Infinity);
    if (validatedArray.length < (rules.minLength ?? 1)) {
        logger.warn(
            `${name}.${key} contains fewer items than allowed (${rules.minLength}). Using default value.`
        );
        return new Set(fieldSchema.default);
    }
    return new Set(validatedArray);
}

function validateObject(configValue, rules, fieldSchema, name, key, validateSchemaFn, logger) {
    if (typeof configValue !== "object" || Array.isArray(configValue)) {
        logger.warn(`${name}.${key} is not a valid object. Using default value.`);
        return fieldSchema.default;
    }
    if (rules.schema) {
        return validateSchemaFn(configValue || {}, rules.schema, `${name}.${key}`);
    } else {
        logger.warn(`${name}.${key} is an object with no schema. Using default value.`);
        return fieldSchema.default;
    }
}

module.exports = { validateArray, validateSet, validateObject };
