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 Response from "../Utils/Response";
import BadDataException from "../../Types/Exception/BadDataException";
import GlobalConfigService from "../Services/GlobalConfigService";
import ObjectID from "../../Types/ObjectID";
import crypto from "crypto";
import logger, { getLogAttributesFromRequest } from "../Utils/Logger";
import CaptureSpan from "../Utils/Telemetry/CaptureSpan";
export default class WhatsAppAuthorization {
    static async isAuthorizedWhatsAppRequest(req, res, next) {
        var _a;
        logger.debug("Starting WhatsApp webhook signature verification", getLogAttributesFromRequest(req));
        const signature = req.headers["x-hub-signature-256"];
        if (!signature) {
            logger.error("WhatsApp webhook request missing X-Hub-Signature-256 header.", getLogAttributesFromRequest(req));
            return Response.sendErrorResponse(req, res, new BadDataException("Missing X-Hub-Signature-256 header."));
        }
        const globalConfig = await GlobalConfigService.findOneBy({
            query: {
                _id: ObjectID.getZeroObjectID().toString(),
            },
            props: {
                isRoot: true,
            },
            select: {
                metaWhatsAppAppSecret: true,
            },
        });
        const appSecret = ((_a = globalConfig === null || globalConfig === void 0 ? void 0 : globalConfig.metaWhatsAppAppSecret) === null || _a === void 0 ? void 0 : _a.trim()) || undefined;
        if (!appSecret) {
            logger.error("Meta WhatsApp App Secret is not configured. Cannot verify webhook signature.", getLogAttributesFromRequest(req));
            return Response.sendErrorResponse(req, res, new BadDataException("Meta WhatsApp App Secret is not configured."));
        }
        const rawBody = req.rawBody || "";
        const expectedSignature = `sha256=${crypto.createHmac("sha256", appSecret).update(rawBody).digest("hex")}`;
        if (!crypto.timingSafeEqual(Buffer.from(expectedSignature), Buffer.from(signature))) {
            logger.error("WhatsApp webhook signature verification failed.", getLogAttributesFromRequest(req));
            return Response.sendErrorResponse(req, res, new BadDataException("WhatsApp webhook signature verification failed."));
        }
        logger.debug("WhatsApp webhook signature verified successfully", getLogAttributesFromRequest(req));
        next();
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Object, Function]),
    __metadata("design:returntype", Promise)
], WhatsAppAuthorization, "isAuthorizedWhatsAppRequest", null);
//# sourceMappingURL=WhatsAppAuthorization.js.map