/*
 * Copyright (c) 2022.
 * Author Peter Placzek (tada5hi)
 * For the full copyright and license information,
 * view the LICENSE file that was distributed with this source code.
 */

import dotenv from "dotenv";

const envResult = dotenv.config();
if (envResult.error) {
    console.error('[ERROR] env failed to load:' + envResult.error);
}

export function requireFromEnv(key : string, alt?: string) {
    if (!process.env[key] && typeof alt === 'undefined') {
        console.error('[APP ERROR] Missing env variable:'+key)

        return process.exit(1)
    }

    return process.env.hasOwnProperty(key) ? process.env[key] : alt;
}

export interface Environment {
    env: string,
    port: number,
    swaggerDocumentation: boolean | null,

    redisConnectionString: string,
    rabbitMqConnectionString: string,

    jwtMaxAge: number,

    apiUrl: string,
}

const jwtMaxAge : number = parseInt(requireFromEnv('JWT_MAX_AGE', '3600'));

const env : Environment = {
    env: requireFromEnv('NODE_ENV'),
    port: parseInt(requireFromEnv('PORT'), 10),
    swaggerDocumentation: requireFromEnv('SWAGGER_DOCUMENTATION', 'false') !== 'false',

    redisConnectionString: requireFromEnv('REDIS_CONNECTION_STRING'),
    rabbitMqConnectionString: requireFromEnv('RABBITMQ_CONNECTION_STRING'),

    jwtMaxAge: Number.isNaN(jwtMaxAge) ? 3600 : jwtMaxAge,

    apiUrl: requireFromEnv('API_URL'),
};

export default env;
