"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.loadConfig = loadConfig;
exports.loadOfficeProfile = loadOfficeProfile;
exports.settlementOfficeId = settlementOfficeId;
exports.port = port;
exports.settlementStoreSubdir = settlementStoreSubdir;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
let cached = null;
let cachedOffice = null;
function repoConfigPath(relative) {
    return path_1.default.resolve(__dirname, '../../../', relative.replace(/^\//, ''));
}
function loadConfig() {
    if (cached)
        return cached;
    const configPath = process.env.SETTLEMENT_MIDDLEWARE_CONFIG ||
        repoConfigPath('config/settlement-middleware.v1.json');
    cached = JSON.parse(fs_1.default.readFileSync(configPath, 'utf8'));
    return cached;
}
function loadOfficeProfile() {
    if (cachedOffice)
        return cachedOffice;
    const cfg = loadConfig();
    const profileRel = cfg.settlementOffice?.profilePath ?? 'config/offices/office-24-settlement.v1.json';
    const profilePath = process.env.OMNL_OFFICE_SETTLEMENT_PROFILE || repoConfigPath(profileRel);
    cachedOffice = JSON.parse(fs_1.default.readFileSync(profilePath, 'utf8'));
    return cachedOffice;
}
/** All settlement runs behind Office 24 (Ali HOSPITALLERS). */
function settlementOfficeId(requested) {
    const cfg = loadConfig();
    const profile = loadOfficeProfile();
    const locked = cfg.settlementOffice?.officeId ?? profile.officeId ?? cfg.defaultOfficeId;
    const fromEnv = parseInt(process.env.ALI_HOSPITALLERS_OFFICE_ID ||
        process.env.OMNL_SETTLEMENT_OFFICE_ID ||
        String(locked), 10);
    const officeId = fromEnv || locked;
    if (cfg.enforceSingleOffice && requested !== undefined && requested !== officeId) {
        throw new Error(`Settlement is locked to office ${officeId}; requested ${requested}`);
    }
    if (cfg.enforceSingleOffice && officeId !== locked) {
        throw new Error(`Settlement is locked to office ${locked}; env specifies ${officeId}`);
    }
    return officeId;
}
function port() {
    return parseInt(process.env.SETTLEMENT_MIDDLEWARE_PORT || '3011', 10);
}
function settlementStoreSubdir() {
    return `office-${settlementOfficeId()}`;
}
