var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import ProjectSCIMService from "../Services/ProjectSCIMService";
import StatusPageSCIMService from "../Services/StatusPageSCIMService";
import ObjectID from "../../Types/ObjectID";
import NotAuthorizedException from "../../Types/Exception/NotAuthorizedException";
import BadRequestException from "../../Types/Exception/BadRequestException";
import CaptureSpan from "../Utils/Telemetry/CaptureSpan";
import logger, { getLogAttributesFromRequest } from "../Utils/Logger";
export default class SCIMMiddleware {
    static async isAuthorizedSCIMRequest(req, _res, next) {
        var _a;
        try {
            const oneuptimeRequest = req;
            // Extract SCIM ID from URL path (could be project or status page)
            const scimId = req.params["projectScimId"] || req.params["statusPageScimId"];
            if (!scimId) {
                throw new BadRequestException("SCIM ID is required");
            }
            // Extract bearer token from Authorization header
            let bearerToken;
            if ((_a = req.headers) === null || _a === void 0 ? void 0 : _a["authorization"]) {
                const authHeader = req.headers["authorization"];
                if (authHeader.startsWith("Bearer ")) {
                    bearerToken = authHeader.substring(7);
                }
            }
            logger.debug(`SCIM Authorization: scimId=${scimId}, bearerToken=${bearerToken ? "***" : "missing"}`, getLogAttributesFromRequest(req));
            if (!bearerToken) {
                throw new NotAuthorizedException("Bearer token is required for SCIM authentication");
            }
            // Try to find Project SCIM configuration first
            const projectScimConfig = await ProjectSCIMService.findOneBy({
                query: {
                    _id: new ObjectID(scimId),
                    bearerToken: bearerToken,
                },
                select: {
                    _id: true,
                    projectId: true,
                    autoProvisionUsers: true,
                    autoDeprovisionUsers: true,
                    enablePushGroups: true,
                    teams: {
                        _id: true,
                        name: true,
                    },
                },
                props: {
                    isRoot: true,
                },
            });
            if (projectScimConfig) {
                // Store Project SCIM configuration
                oneuptimeRequest.bearerTokenData = {
                    scimConfig: projectScimConfig,
                    projectId: projectScimConfig.projectId,
                    projectScimId: new ObjectID(scimId),
                    type: "project-scim",
                };
                return next();
            }
            // If not found, try Status Page SCIM configuration
            const statusPageScimConfig = await StatusPageSCIMService.findOneBy({
                query: {
                    _id: new ObjectID(scimId),
                    bearerToken: bearerToken,
                },
                select: {
                    _id: true,
                    projectId: true,
                    statusPageId: true,
                    autoProvisionUsers: true,
                    autoDeprovisionUsers: true,
                },
                props: {
                    isRoot: true,
                },
            });
            if (statusPageScimConfig) {
                // Store Status Page SCIM configuration
                oneuptimeRequest.bearerTokenData = {
                    scimConfig: statusPageScimConfig,
                    projectId: statusPageScimConfig.projectId,
                    statusPageId: statusPageScimConfig.statusPageId,
                    statusPageScimId: new ObjectID(scimId),
                    type: "status-page-scim",
                };
                return next();
            }
            // If neither found, throw error
            throw new NotAuthorizedException("Invalid bearer token or SCIM configuration not found");
        }
        catch (err) {
            return next(err);
        }
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Object, Function]),
    __metadata("design:returntype", Promise)
], SCIMMiddleware, "isAuthorizedSCIMRequest", null);
//# sourceMappingURL=SCIMAuthorization.js.map