/**
 * Mail Configuration
 * Runtime mail drivers and settings
 * Sealed namespace for immutability
 */
import { Env } from './env.js';
import { ErrorFactory } from '../exceptions/ZintrustError.js';
import { StartupConfigFile, StartupConfigFileRegistry } from '../runtime/StartupConfigFileRegistry.js';
const isMailDriverConfig = (value) => {
    if (typeof value !== 'object' || value === null)
        return false;
    if (!('driver' in value))
        return false;
    const driver = value.driver;
    return typeof driver === 'string' && driver.trim().length > 0;
};
const getMailDriver = (config, name) => {
    const drivers = config.drivers;
    const envSelectedRaw = Env.get('MAIL_CONNECTION', Env.get('MAIL_DRIVER', '')).trim();
    const selected = (name ??
        (envSelectedRaw.length > 0 ? envSelectedRaw : undefined) ??
        config.default)
        .toString()
        .trim();
    if (selected.length === 0) {
        const disabled = drivers['disabled'];
        if (isMailDriverConfig(disabled))
            return disabled;
        throw ErrorFactory.createConfigError('Mail driver not configured: disabled');
    }
    if (Object.hasOwn(drivers, selected)) {
        const resolved = drivers[selected];
        if (isMailDriverConfig(resolved))
            return resolved;
    }
    throw ErrorFactory.createConfigError(`Mail driver not configured: ${selected}`);
};
/**
 * Create base mail drivers configuration
 */
const createMailDrivers = () => {
    return {
        disabled: {
            driver: 'disabled',
        },
        sendgrid: {
            driver: 'sendgrid',
            apiKey: Env.get('SENDGRID_API_KEY', ''),
        },
        mailgun: {
            driver: 'mailgun',
            apiKey: Env.get('MAILGUN_API_KEY', ''),
            domain: Env.get('MAILGUN_DOMAIN', ''),
            baseUrl: Env.get('MAILGUN_BASE_URL', 'https://api.mailgun.net').trim(),
        },
        smtp: {
            driver: 'smtp',
            host: Env.get('MAIL_HOST', ''),
            port: Env.getInt('MAIL_PORT', 587),
            username: Env.get('MAIL_USERNAME', ''),
            password: Env.get('MAIL_PASSWORD', ''),
            secure: (() => {
                const raw = Env.get('MAIL_SECURE', '').trim().toLowerCase();
                if (raw === 'starttls')
                    return 'starttls';
                if (raw === 'tls' || raw === 'ssl' || raw === 'smtps' || raw === 'implicit')
                    return true;
                if (raw === 'none' || raw === 'off' || raw === 'false' || raw === '0')
                    return false;
                return Env.getBool('MAIL_SECURE', false);
            })(),
        },
        nodemailer: {
            driver: 'nodemailer',
            host: Env.get('MAIL_HOST', ''),
            port: Env.getInt('MAIL_PORT', 587),
            username: Env.get('MAIL_USERNAME', ''),
            password: Env.get('MAIL_PASSWORD', ''),
            secure: (() => {
                const raw = Env.get('MAIL_SECURE', '').trim().toLowerCase();
                if (raw === 'starttls')
                    return 'starttls';
                if (raw === 'tls' || raw === 'ssl' || raw === 'smtps' || raw === 'implicit')
                    return true;
                if (raw === 'none' || raw === 'off' || raw === 'false' || raw === '0')
                    return false;
                return Env.getBool('MAIL_SECURE', false);
            })(),
        },
        ses: {
            driver: 'ses',
            region: Env.get('AWS_REGION', 'us-east-1'),
        },
    };
};
const createMailConfig = () => {
    const overrides = StartupConfigFileRegistry.get(StartupConfigFile.Mail) ?? {};
    const baseDefault = Env.get('MAIL_CONNECTION', Env.get('MAIL_DRIVER', 'disabled'))
        .trim()
        .toLowerCase();
    const baseFrom = {
        address: Env.get('MAIL_FROM_ADDRESS', ''),
        name: Env.get('MAIL_FROM_NAME', ''),
    };
    const baseDrivers = createMailDrivers();
    const mailConfigObj = {
        /**
         * Default mail driver
         */
        default: (overrides.default ?? baseDefault).trim().toLowerCase(),
        /**
         * Default "From" identity
         */
        from: {
            ...baseFrom,
            ...overrides.from,
        },
        /**
         * Driver configs
         */
        drivers: {
            ...baseDrivers,
            ...overrides.drivers,
        },
        /**
         * Get selected driver config
         */
        getDriver(name) {
            return getMailDriver(this, name);
        },
    };
    return Object.freeze(mailConfigObj);
};
let cached = null;
const proxyTarget = {};
const ensureMailConfig = () => {
    if (cached)
        return cached;
    cached = createMailConfig();
    try {
        Object.defineProperties(proxyTarget, Object.getOwnPropertyDescriptors(cached));
    }
    catch {
        // best-effort
    }
    return cached;
};
export const mailConfig = new Proxy(proxyTarget, {
    get(_target, prop) {
        return ensureMailConfig()[prop];
    },
    ownKeys() {
        ensureMailConfig();
        return Reflect.ownKeys(proxyTarget);
    },
    getOwnPropertyDescriptor(_target, prop) {
        ensureMailConfig();
        return Object.getOwnPropertyDescriptor(proxyTarget, prop);
    },
});
