"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.apiKey = apiKey;
exports.requireScope = requireScope;
exports.requireSuperAdmin = requireSuperAdmin;
exports.requireRead = requireRead;
exports.requireTrade = requireTrade;
const integration_foundation_1 = require("@dbis/integration-foundation");
const config_1 = require("../config");
function apiKey(req) {
    return (0, integration_foundation_1.extractApiKey)(req);
}
function requireScope(req, res, scope) {
    const cfg = (0, config_1.loadExchangeConfig)();
    if (!cfg.production.requireApiKey && !(0, integration_foundation_1.isProductionSecurityMode)())
        return true;
    const policy = (0, integration_foundation_1.loadCustomerSecurityPolicy)();
    if (policy.requireApiKeyAllExchangeRoutes || cfg.production.requireApiKey) {
        const principal = (0, integration_foundation_1.resolveOmnlPrincipal)(req);
        if (!principal) {
            res.status(401).json({ error: 'Unauthorized', hint: 'Valid customer or super-admin API key required' });
            return false;
        }
        if (!(0, integration_foundation_1.principalHasScope)(principal, scope)) {
            res.status(403).json({ error: 'Forbidden', scope, role: principal.role });
            return false;
        }
        return true;
    }
    return true;
}
function requireSuperAdmin(req, res) {
    return requireScope(req, res, 'admin');
}
function requireRead(req, res) {
    return requireScope(req, res, 'read');
}
function requireTrade(req, res) {
    return requireScope(req, res, 'trade');
}
