import * as path from '../node-singletons/path.js';
import mergeOverrideValues from './OverrideValueMerge.js';
import { ProjectRuntime } from './ProjectRuntime.js';
import useFileLoader from './useFileLoader.js';
// NOTE runtime config loader
export const StartupConfigFile = {
    Broadcast: 'config/broadcast.ts',
    Cache: 'config/cache.ts',
    Database: 'config/database.ts',
    Mail: 'config/mail.ts',
    Middleware: 'config/middleware.ts',
    Notification: 'config/notification.ts',
    Queue: 'config/queue.ts',
    Storage: 'config/storage.ts',
    Workers: 'config/workers.ts',
};
const cache = new Map();
let preloaded = false;
const getWorkersStartupOverrides = () => {
    if (typeof globalThis === 'undefined')
        return undefined;
    const globalAny = globalThis;
    return globalAny.__zintrustStartupConfigOverrides;
};
const getServiceConfigFile = (file) => {
    const activeService = ProjectRuntime.getActiveService();
    if (activeService?.configRoot === undefined || activeService.configRoot.trim() === '') {
        return undefined;
    }
    return `${activeService.configRoot}/${path.basename(file)}`;
};
const loadStartupOverride = async (file) => {
    const overrides = getWorkersStartupOverrides();
    if (overrides?.has(file) === true) {
        return overrides.get(file);
    }
    const rootLoader = useFileLoader(file);
    const serviceFile = getServiceConfigFile(file);
    const serviceLoader = serviceFile === undefined ? undefined : useFileLoader(serviceFile);
    const hasRoot = rootLoader.exists();
    const hasService = serviceLoader?.exists() === true;
    if (!hasRoot && !hasService) {
        return undefined;
    }
    const rootOverride = hasRoot ? await rootLoader.get() : undefined;
    const serviceOverride = hasService && serviceLoader !== undefined ? await serviceLoader.get() : undefined;
    if (rootOverride === undefined)
        return serviceOverride;
    if (serviceOverride === undefined)
        return rootOverride;
    return mergeOverrideValues(rootOverride, serviceOverride);
};
export const StartupConfigFileRegistry = Object.freeze({
    async preload(files) {
        const tasks = files.map(async (file) => {
            const value = await loadStartupOverride(file);
            if (value === undefined) {
                cache.delete(file);
                return;
            }
            cache.set(file, value);
        });
        await Promise.all(tasks);
        preloaded = true;
    },
    isPreloaded() {
        return preloaded;
    },
    get(file) {
        return cache.get(file);
    },
    has(file) {
        return cache.has(file);
    },
    /** Intended for tests only. */
    clear() {
        cache.clear();
        preloaded = false;
    },
});
export default StartupConfigFileRegistry;
