"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.applyDatabaseConfig = applyDatabaseConfig;
exports.applyServerAuthConfig = applyServerAuthConfig;
const config_1 = require("../modules/config");
const auth_1 = require("../modules/auth");
const logger_1 = require("../lib/logger");
/**
 * Apply database connection settings from the startup config
 * to the shared postgres_options object.
 */
function applyDatabaseConfig(db) {
    if (db.connectionString) {
        // Infer SSL from sslmode in connection string when not explicitly provided
        if (!db.ssl) {
            try {
                const sslmode = new URL(db.connectionString).searchParams.get('sslmode');
                if (sslmode === 'require') {
                    config_1.postgres_options.ssl = { rejectUnauthorized: false };
                    logger_1.loggerRegistry.info('[long-tail] database SSL inferred from sslmode=require');
                }
            }
            catch { /* not a parseable URL — skip inference */ }
        }
        // Clear individual fields — connectionString takes precedence.
        // Delete stale keys so pg doesn't see conflicting host/port/etc.
        delete config_1.postgres_options.host;
        delete config_1.postgres_options.port;
        delete config_1.postgres_options.user;
        delete config_1.postgres_options.password;
        delete config_1.postgres_options.database;
        config_1.postgres_options.connectionString = db.connectionString;
    }
    else {
        config_1.postgres_options.host = db.host ?? config_1.postgres_options.host;
        config_1.postgres_options.port = db.port ?? config_1.postgres_options.port;
        config_1.postgres_options.user = db.user ?? config_1.postgres_options.user;
        config_1.postgres_options.password = db.password ?? config_1.postgres_options.password;
        config_1.postgres_options.database = db.database ?? config_1.postgres_options.database;
    }
    // SSL passthrough — applies to both connectionString and individual-field modes
    if (db.ssl !== undefined) {
        config_1.postgres_options.ssl = db.ssl;
        logger_1.loggerRegistry.info(`[long-tail] database SSL configured: ${typeof db.ssl === 'object' ? JSON.stringify(db.ssl) : db.ssl}`);
    }
}
/**
 * Apply server port and auth settings from the startup config.
 */
async function applyServerAuthConfig(startConfig) {
    const serverPort = startConfig.server?.port ?? config_1.config.PORT;
    config_1.config.PORT = serverPort;
    if (startConfig.auth?.secret) {
        config_1.config.JWT_SECRET = startConfig.auth.secret;
    }
    if (startConfig.auth?.adapter) {
        (0, auth_1.setAuthAdapter)(startConfig.auth.adapter);
    }
    // Initialize OAuth providers (from startup config and/or env vars)
    const { initializeOAuth } = await Promise.resolve().then(() => __importStar(require('../services/oauth')));
    initializeOAuth(startConfig.auth?.oauth);
    if (startConfig.auth?.oauth) {
        const { setOAuthConfig } = await Promise.resolve().then(() => __importStar(require('../routes/oauth')));
        setOAuthConfig({
            autoProvision: startConfig.auth.oauth.autoProvision,
            defaultRoleType: startConfig.auth.oauth.defaultRoleType,
            baseUrl: startConfig.auth.oauth.baseUrl,
        });
    }
}
