"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CustomConfigLoader = void 0;
function __assignType(fn, args) {
    fn.__type = args;
    return fn;
}
const app_1 = require("@deepkit/app");
const type_1 = require("@deepkit/type");
const config_1 = require("@zyno-io/config");
const fs_1 = require("fs");
const lodash_1 = require("lodash");
const const_1 = require("./const");
class CustomConfigLoader {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    constructor(defaultConfig) {
        this.defaultConfig = defaultConfig;
        this.configLoaded = false;
    }
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    load(_module, config, schema) {
        if (this.configLoaded) {
            return;
        }
        if (this.defaultConfig) {
            Object.assign(config, this.defaultConfig);
        }
        const loadedConfig = this.loadConfigObject();
        // copy the keys from the schema over, and DK will validate it after
        for (const prop of schema.getProperties()) {
            if (prop.name in loadedConfig) {
                config[prop.name] = loadedConfig[prop.name];
            }
        }
        this.configLoaded = true;
    }
    loadConfigObject() {
        if (!process.env.APP_ENV) {
            if (process.argv.includes('--test')) {
                process.env.APP_ENV = 'test';
            }
            else {
                throw new Error('APP_ENV must be specified in the environment');
            }
        }
        const cwd = process.cwd();
        const configFiles = (0, lodash_1.compact)([
            `.env`,
            `.env.local`,
            const_1.isTest && `.env.development`,
            const_1.isTest && `.env.development.local`,
            `.env.${process.env.APP_ENV}`,
            `.env.${process.env.APP_ENV}.local`
        ]);
        const configPaths = configFiles.map(__assignType(file => `${cwd}/${file}`, ['file', '', 'P"2!"/"']));
        const validConfigPaths = configPaths.filter(__assignType(path => (0, fs_1.existsSync)(path), ['path', '', 'P"2!"/"']));
        if (validConfigPaths.length === 0) {
            return process.env;
        }
        return (0, config_1.loadConfig)({
            file: validConfigPaths
        });
    }
}
exports.CustomConfigLoader = CustomConfigLoader;
CustomConfigLoader.__type = ['configLoaded', function () { return false; }, 'defaultConfig', 'constructor', () => app_1.AppModule, '_module', 'config', () => type_1.ReflectionClass, 'schema', 'load', 'loadConfigObject', 'CustomConfigLoader', ')3!;>"PP&"LM2#8;"0$PP"7%2&P&"LM2\'P"7(2)"0*P"0+<5w,'];
//# sourceMappingURL=config.loader.js.map