"use strict";
// backend/src/routes/providerRoutes.ts
// SPDX-License-Identifier: AGPL-3.0-or-later
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = __importDefault(require("express"));
const providerManager_1 = require("../services/providerManager");
const connectionTester_1 = require("../services/providerManager/connectionTester");
const auth_1 = require("../middleware/auth");
const enterpriseAuditService_1 = require("../services/enterpriseAuditService");
const rbac_1 = require("../services/rbac");
const router = express_1.default.Router();
router.use(auth_1.authenticate);
router.use((req, res, next) => {
    const context = (0, auth_1.requireRequestContext)(req);
    if (!(0, rbac_1.hasRbacPermission)(context, 'provider:manage_workspace')) {
        (0, rbac_1.sendForbidden)(res, 'Provider management requires provider:manage_workspace permission');
        return;
    }
    next();
});
function providerScopeForRequest(req) {
    const context = (0, auth_1.requireRequestContext)(req);
    const workspaceRouteContext = req.workspaceRouteContext;
    return {
        tenantId: context.tenantId,
        workspaceId: context.workspaceId,
        ...(workspaceRouteContext ? {} : { userId: context.userId }),
    };
}
function recordProviderAudit(context, action, providerId, metadata = {}) {
    (0, enterpriseAuditService_1.recordEnterpriseAuditEventForContext)(context, {
        action,
        resourceType: 'provider',
        resourceId: providerId,
        metadata,
    });
}
router.get('/', (req, res) => {
    const svc = (0, providerManager_1.getProviderService)();
    res.json({ success: true, providers: svc.list(providerScopeForRequest(req)) });
});
router.get('/templates', (_req, res) => {
    res.json({ success: true, templates: providerManager_1.officialTemplates });
});
router.get('/effective', (req, res) => {
    const svc = (0, providerManager_1.getProviderService)();
    const scope = providerScopeForRequest(req);
    const env = svc.getEffectiveEnv(scope);
    if (env) {
        const active = svc.list(scope).find(p => p.isActive);
        res.json({ success: true, source: 'provider-manager', provider: active, env: maskEnvKeys(env) });
    }
    else {
        res.json({ success: true, source: 'env-fallback', provider: null });
    }
});
router.get('/:id', (req, res) => {
    const svc = (0, providerManager_1.getProviderService)();
    const context = (0, auth_1.requireRequestContext)(req);
    const provider = svc.get(req.params.id, providerScopeForRequest(req));
    if (!provider)
        return res.status(404).json({ success: false, error: 'Provider not found' });
    recordProviderAudit(context, 'provider.read', provider.id, {
        type: provider.type,
        active: provider.isActive,
    });
    res.json({ success: true, provider });
});
router.post('/', (req, res) => {
    try {
        const svc = (0, providerManager_1.getProviderService)();
        const input = req.body;
        const context = (0, auth_1.requireRequestContext)(req);
        const scope = providerScopeForRequest(req);
        const provider = svc.create(input, scope);
        recordProviderAudit(context, 'provider.created', provider.id, {
            type: provider.type,
            category: provider.category,
            runtime: provider.connection.agentRuntime,
        });
        res.status(201).json({ success: true, provider: svc.get(provider.id, scope) });
    }
    catch (err) {
        res.status(400).json({ success: false, error: err.message });
    }
});
router.patch('/:id', (req, res) => {
    try {
        const svc = (0, providerManager_1.getProviderService)();
        const input = req.body;
        const context = (0, auth_1.requireRequestContext)(req);
        const scope = providerScopeForRequest(req);
        const updated = svc.update(req.params.id, input, scope);
        recordProviderAudit(context, 'provider.updated', updated.id, {
            type: updated.type,
            changedFields: Object.keys(input),
        });
        res.json({ success: true, provider: svc.get(req.params.id, scope) });
    }
    catch (err) {
        const status = err.message.includes('not found') ? 404 : 400;
        res.status(status).json({ success: false, error: err.message });
    }
});
router.delete('/:id', (req, res) => {
    try {
        const svc = (0, providerManager_1.getProviderService)();
        const context = (0, auth_1.requireRequestContext)(req);
        const scope = providerScopeForRequest(req);
        const existing = svc.get(req.params.id, scope);
        svc.delete(req.params.id, scope);
        recordProviderAudit(context, 'provider.deleted', req.params.id, {
            type: existing?.type,
        });
        res.json({ success: true });
    }
    catch (err) {
        const status = err.message.includes('not found') ? 404 : 400;
        res.status(status).json({ success: false, error: err.message });
    }
});
router.post('/deactivate', (req, res) => {
    const svc = (0, providerManager_1.getProviderService)();
    const context = (0, auth_1.requireRequestContext)(req);
    const scope = providerScopeForRequest(req);
    const active = svc.list(scope).find(provider => provider.isActive);
    svc.deactivateAll(scope);
    recordProviderAudit(context, 'provider.deactivated', active?.id, {
        type: active?.type,
    });
    res.json({ success: true });
});
router.post('/:id/activate', (req, res) => {
    try {
        const svc = (0, providerManager_1.getProviderService)();
        const context = (0, auth_1.requireRequestContext)(req);
        const scope = providerScopeForRequest(req);
        svc.activate(req.params.id, scope);
        const provider = svc.get(req.params.id, scope);
        recordProviderAudit(context, 'provider.activated', req.params.id, {
            type: provider?.type,
        });
        res.json({ success: true });
    }
    catch (err) {
        const status = err.message.includes('not found') ? 404 : 400;
        res.status(status).json({ success: false, error: err.message });
    }
});
router.post('/:id/runtime', (req, res) => {
    try {
        const svc = (0, providerManager_1.getProviderService)();
        const runtime = req.body?.agentRuntime;
        if (runtime !== 'claude-agent-sdk' && runtime !== 'openai-agents-sdk') {
            return res.status(400).json({ success: false, error: 'Invalid agentRuntime' });
        }
        const context = (0, auth_1.requireRequestContext)(req);
        const scope = providerScopeForRequest(req);
        const provider = svc.switchAgentRuntime(req.params.id, runtime, scope);
        recordProviderAudit(context, 'provider.runtime_switched', req.params.id, {
            type: provider.type,
            runtime,
        });
        res.json({ success: true, provider: svc.get(req.params.id, scope) });
    }
    catch (err) {
        const status = err.message.includes('not found') ? 404 : 400;
        res.status(status).json({ success: false, error: err.message });
    }
});
router.post('/:id/rotate-secret', (req, res) => {
    try {
        const svc = (0, providerManager_1.getProviderService)();
        const context = (0, auth_1.requireRequestContext)(req);
        const scope = providerScopeForRequest(req);
        const secretVersion = svc.rotateSecret(req.params.id, scope);
        const provider = svc.get(req.params.id, scope);
        recordProviderAudit(context, 'provider.secret_rotated', req.params.id, {
            type: provider?.type,
            secretVersion,
        });
        res.json({ success: true, secretVersion, provider: svc.get(req.params.id, scope) });
    }
    catch (err) {
        const status = err.message.includes('not found') ? 404 : 400;
        res.status(status).json({ success: false, error: err.message });
    }
});
router.post('/:id/test', async (req, res) => {
    const svc = (0, providerManager_1.getProviderService)();
    const context = (0, auth_1.requireRequestContext)(req);
    const provider = svc.getRaw(req.params.id, providerScopeForRequest(req));
    if (!provider)
        return res.status(404).json({ success: false, error: 'Provider not found' });
    const result = await (0, connectionTester_1.testProviderConnection)(provider);
    recordProviderAudit(context, 'provider.connection_tested', req.params.id, {
        type: provider.type,
        success: result.success,
    });
    res.json({ success: true, result });
});
function maskEnvKeys(env) {
    const masked = {};
    const sensitivePatterns = ['KEY', 'TOKEN', 'SECRET'];
    for (const [k, v] of Object.entries(env)) {
        if (sensitivePatterns.some(p => k.includes(p)) && v.length > 8) {
            masked[k] = `****${v.slice(-4)}`;
        }
        else {
            masked[k] = v;
        }
    }
    return masked;
}
exports.default = router;
//# sourceMappingURL=providerRoutes.js.map