'use strict';

const Assert = require('assert');
const Joi = require('joi');


const initMainConfig = () => {
    const config = require('dotenv').config();

    if (config.error) {
        console.error('Failed to read config file: ' + config.error);
    } else {
        console.log(`Config file loaded with ${config.parsed ? Object.keys(config.parsed).length : 0} options`);
    }
};

const initConfigs = (configs = []) => {
    Assert.ok(configs && Array.isArray(configs), '\'configs\' must be an array');

    initMainConfig();

    configs.forEach( c => {
        try {
            if (c) {
                Assert.ok(Joi.isSchema(c), 'config must be a Joi schema');

                const result = c.validate(process.env, {
                    allowUnknown: true,
                    presence: 'required'
                });

                if (result.error) {
                    throw result.error;
                }

                if (result.value) {
                    process.env = {...process.env, ...result.value};
                }
            }
        } catch (e) {
            throw new Joi.ValidationError(`Failed to validate config: ${e}`);
        }
    });
};

module.exports = initConfigs;
