import { existsSync, readFileSync } from 'node:fs';
import { parse } from 'yaml';
function parseServerConfig(raw) {
    return {
        host: raw.host,
        plan: raw.plan,
    };
}
function parseTargetConfig(raw) {
    const target = {
        dir: raw.dir,
        dnsRecordType: (raw.dns_record_type ?? 'A'),
        dnsValue: raw.dns_value,
        dnsZone: raw.dns_zone,
        domain: raw.domain,
        dotEnvEnc: raw.dot_env_enc,
        envConfiguration: raw.env_configuration,
        ftpLogin: raw.ftp_login,
        startupFile: raw.startup_file,
    };
    if (raw.database) {
        target.database = {
            name: raw.database.name,
            type: raw.database.type,
            user: raw.database.user,
        };
    }
    return target;
}
export function loadConfig(configPath) {
    if (!existsSync(configPath)) {
        throw new Error(`Config file not found: ${configPath}`);
    }
    const raw = parse(readFileSync(configPath, 'utf8'));
    if (!raw.environments || Object.keys(raw.environments).length === 0) {
        throw new Error('Config error: "environments" block is required with at least one environment.');
    }
    const server = parseServerConfig(raw.server);
    const config = {
        environments: new Map(),
        project: {
            email: raw.project.email,
            name: raw.project.name,
            repo: raw.project.repo,
        },
        server,
    };
    if (raw.sheets?.bounded_contexts) {
        const boundedContexts = {};
        for (const [name, rawBc] of Object.entries(raw.sheets.bounded_contexts)) {
            boundedContexts[name] = {
                description: rawBc.description,
                spreadsheetId: rawBc.spreadsheet_id,
            };
        }
        config.sheets = { boundedContexts };
    }
    for (const [envName, rawEnv] of Object.entries(raw.environments)) {
        const envServer = rawEnv.server
            ? parseServerConfig(rawEnv.server)
            : server;
        const envConfig = {
            server: envServer,
            source: rawEnv.source ?? 'main',
        };
        if (rawEnv.back) {
            envConfig.back = parseTargetConfig(rawEnv.back);
        }
        if (rawEnv.front) {
            envConfig.front = parseTargetConfig(rawEnv.front);
        }
        config.environments.set(envName, envConfig);
    }
    return config;
}
