"use strict";
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2024-2026 Gracker (Chris)
// This file is part of SmartPerfetto. See LICENSE for details.
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createEnterpriseApiKeyRouter = createEnterpriseApiKeyRouter;
const express_1 = __importDefault(require("express"));
const auth_1 = require("../middleware/auth");
const enterpriseApiKeyService_1 = require("../services/enterpriseApiKeyService");
function hasScope(context, scope) {
    return context.scopes.includes('*') || context.scopes.includes(scope);
}
function canReadApiKeys(context) {
    return hasScope(context, 'api_key:read')
        || hasScope(context, 'api_key:write')
        || context.roles.includes('workspace_admin')
        || context.roles.includes('org_admin');
}
function canWriteApiKeys(context) {
    return hasScope(context, 'api_key:write')
        || context.roles.includes('workspace_admin')
        || context.roles.includes('org_admin');
}
function forbidden(res) {
    res.status(403).json({
        success: false,
        error: 'Forbidden',
        details: 'API key management requires api_key:write scope or workspace/org admin role',
    });
}
function createInputFromBody(body) {
    return {
        name: typeof body?.name === 'string' ? body.name : undefined,
        workspaceId: body?.workspaceId === null || typeof body?.workspaceId === 'string'
            ? body.workspaceId
            : undefined,
        ownerUserId: body?.ownerUserId === null || typeof body?.ownerUserId === 'string'
            ? body.ownerUserId
            : undefined,
        scopes: body?.scopes,
        expiresAt: body?.expiresAt,
    };
}
function firstParam(value) {
    return Array.isArray(value) ? value[0] || '' : value || '';
}
function createEnterpriseApiKeyRouter(deps = {}) {
    const router = express_1.default.Router();
    const getService = () => deps.apiKeyService || enterpriseApiKeyService_1.EnterpriseApiKeyService.getInstance();
    router.get('/api-keys', auth_1.authenticate, (req, res) => {
        const context = (0, auth_1.requireRequestContext)(req);
        if (!canReadApiKeys(context)) {
            forbidden(res);
            return;
        }
        res.json({
            success: true,
            apiKeys: getService().listApiKeys(context),
        });
    });
    router.post('/api-keys', auth_1.authenticate, (req, res) => {
        const context = (0, auth_1.requireRequestContext)(req);
        if (!canWriteApiKeys(context)) {
            forbidden(res);
            return;
        }
        try {
            const created = getService().createApiKey(context, createInputFromBody(req.body));
            res.status(201).json({
                success: true,
                apiKey: created.apiKey,
                token: created.token,
            });
        }
        catch (error) {
            res.status(400).json({
                success: false,
                error: error instanceof Error ? error.message : 'Failed to create API key',
            });
        }
    });
    router.post('/api-keys/:id/revoke', auth_1.authenticate, (req, res) => {
        const context = (0, auth_1.requireRequestContext)(req);
        if (!canWriteApiKeys(context)) {
            forbidden(res);
            return;
        }
        const revoked = getService().revokeApiKey(context, firstParam(req.params.id));
        if (!revoked) {
            res.status(404).json({
                success: false,
                error: 'API key not found',
            });
            return;
        }
        res.json({
            success: true,
            apiKey: revoked,
        });
    });
    router.delete('/api-keys/:id', auth_1.authenticate, (req, res) => {
        const context = (0, auth_1.requireRequestContext)(req);
        if (!canWriteApiKeys(context)) {
            forbidden(res);
            return;
        }
        const revoked = getService().revokeApiKey(context, firstParam(req.params.id));
        if (!revoked) {
            res.status(404).json({
                success: false,
                error: 'API key not found',
            });
            return;
        }
        res.json({
            success: true,
            apiKey: revoked,
        });
    });
    return router;
}
exports.default = createEnterpriseApiKeyRouter();
//# sourceMappingURL=enterpriseApiKeyRoutes.js.map