"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.
Object.defineProperty(exports, "__esModule", { value: true });
exports.ownerFieldsFromContext = ownerFieldsFromContext;
exports.normalizeResourceOwner = normalizeResourceOwner;
exports.isOwnedByContext = isOwnedByContext;
exports.ownersMatch = ownersMatch;
exports.isPrivilegedRequestContext = isPrivilegedRequestContext;
exports.sendResourceNotFound = sendResourceNotFound;
const auth_1 = require("../middleware/auth");
const normalizeOwnerId = (value) => (typeof value === 'string' && value.trim().length > 0 ? value.trim() : '');
function ownerFieldsFromContext(context) {
    return {
        tenantId: context.tenantId,
        workspaceId: context.workspaceId,
        userId: context.userId,
    };
}
function normalizeResourceOwner(resource) {
    return {
        tenantId: normalizeOwnerId(resource?.tenantId) || auth_1.DEFAULT_TENANT_ID,
        workspaceId: normalizeOwnerId(resource?.workspaceId) || auth_1.DEFAULT_WORKSPACE_ID,
        userId: normalizeOwnerId(resource?.userId ?? resource?.ownerUserId) || auth_1.DEFAULT_DEV_USER_ID,
    };
}
function isOwnedByContext(resource, context) {
    const owner = normalizeResourceOwner(resource);
    return owner.tenantId === context.tenantId
        && owner.workspaceId === context.workspaceId
        && owner.userId === context.userId;
}
function ownersMatch(resource, ownerFields) {
    const left = normalizeResourceOwner(resource);
    const right = normalizeResourceOwner(ownerFields);
    return left.tenantId === right.tenantId
        && left.workspaceId === right.workspaceId
        && left.userId === right.userId;
}
function isPrivilegedRequestContext(context) {
    return context.roles.includes('org_admin') || context.scopes.includes('*');
}
function sendResourceNotFound(res, error = 'Resource not found') {
    return res.status(404).json({
        success: false,
        error,
    });
}
//# sourceMappingURL=resourceOwnership.js.map