"use strict";

/*
    Fields middleware
    This module exports a function that takes an optional configuration object parameter with the following
    properties:
    {
            validFields: Array of strings (case sensitive),
            invalidFields: Array of strings (case sensitive),
    }
    and returns an express compatible middleware function (req, res, next) that parses the following
    parameters from the req.query object and sets an object on the res.locals.fields having the following
    properties:
    
        Object - with fields for the attributes value fields
    
*/

const middleware = (config) => {

    config = config || {
        validFields: null,
        invalidFields: null,
    };

    if (config.validFields && (!Array.isArray(config.validFields))) {
        throw new Error("config.validFields should be a non empty array of strings");
    }

    if (config.invalidFields && (!Array.isArray(config.invalidFields))) {
        throw new Error("config.invalidFields should be a non empty array of strings");
    }

    return function (req, res, next) {
        const fieldNames = Array.isArray(req.query.fields)
            ? req.query.fields
            : req.query.fields
                ? [req.query.fields]
                : [];

        const fieldObject = fieldNames.filter(field => {
            let isOk = true;
            if (config.validFields) {
                isOk = config.validFields.includes(field)
            }

            if (config.invalidFields) {
                isOk = !config.invalidFields.includes(field)
            }

            return isOk;
        });

        res.locals.fields = {};

        (Object.keys(fieldObject).length > 0) ? res.locals.fields['fields'] = fieldObject : null;            
        config.invalidFields ? res.locals.fields['invalidFields'] = config.invalidFields : null;
        config.validFields ? res.locals.fields['validFields'] = config.validFields : null,

        next();
    };
}

module.exports = {
    middleware
}