"use strict";
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);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var MetaCloudWhatsappWebhookController_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.MetaCloudWhatsappWebhookController = void 0;
const openapi = require("@nestjs/swagger");
const common_1 = require("@nestjs/common");
const swagger_1 = require("@nestjs/swagger");
const auth_decorator_1 = require("../decorators/auth.decorator");
const public_decorator_1 = require("../decorators/public.decorator");
const auth_type_enum_1 = require("../enums/auth-type.enum");
const setting_service_1 = require("../services/setting.service");
let MetaCloudWhatsappWebhookController = MetaCloudWhatsappWebhookController_1 = class MetaCloudWhatsappWebhookController {
    constructor(settingService) {
        this.settingService = settingService;
        this.logger = new common_1.Logger(MetaCloudWhatsappWebhookController_1.name);
    }
    verifyWebhook(query, res) {
        const mode = this.resolveQueryValue(query, "hub.mode", "hub_mode", "mode");
        const verifyToken = this.resolveQueryValue(query, "hub.verify_token", "hub_verify_token", "verify_token");
        const challenge = this.resolveQueryValue(query, "hub.challenge", "hub_challenge", "challenge");
        const configuredVerifyToken = this.settingService.getConfigValue("metaWhatsappWebhookVerifyToken") || process.env.COMMON_META_WHATSAPP_WEBHOOK_VERIFY_TOKEN;
        const isVerificationCall = mode === "subscribe";
        const tokenMatches = !!configuredVerifyToken && verifyToken === configuredVerifyToken;
        if (isVerificationCall && tokenMatches && challenge) {
            this.logger.log("Meta Cloud WhatsApp webhook verified successfully.");
            res.writeHead(common_1.HttpStatus.OK, {
                "Content-Type": "text/plain",
                "Content-Length": Buffer.byteLength(String(challenge)),
            });
            res.write(String(challenge));
            return res.end();
        }
        this.logger.warn(`Meta Cloud webhook verification failed. mode=${mode ?? "n/a"}, tokenMatch=${tokenMatches}`);
        res.writeHead(common_1.HttpStatus.FORBIDDEN, { "Content-Type": "text/plain" });
        return res.end("Webhook verification failed");
    }
    async receiveWebhook(body) {
        this.logger.log("Received Meta Cloud WhatsApp webhook");
        this.logger.debug(`Meta Cloud webhook payload: ${JSON.stringify(body)}`);
        const statusInfo = this.extractStatusInfo(body);
        if (statusInfo) {
            this.logger.log(`Meta Cloud delivery update: status=${statusInfo.status ?? "unknown"}, messageId=${statusInfo.messageId ?? "n/a"}, destination=${statusInfo.destination ?? "n/a"}, reason=${statusInfo.reason ?? "n/a"}`);
        }
        return {
            success: true,
            message: "Webhook received",
        };
    }
    extractStatusInfo(body) {
        if (!body || typeof body !== "object") {
            return null;
        }
        const payload = body;
        const entries = payload.entry;
        const changes = entries?.[0]?.changes;
        const value = changes?.[0]?.value;
        const statuses = value?.statuses;
        const status = statuses?.[0];
        if (!status) {
            return null;
        }
        const errors = status.errors;
        return {
            status: this.asString(status.status),
            messageId: this.asString(status.id),
            destination: this.asString(status.recipient_id),
            reason: this.asString(errors?.[0]?.title) || this.asString(errors?.[0]?.message),
        };
    }
    asString(value) {
        return typeof value === "string" && value.trim() ? value.trim() : undefined;
    }
    resolveQueryValue(query, ...keys) {
        for (const key of keys) {
            const directValue = this.asString(query[key]);
            if (directValue) {
                return directValue;
            }
        }
        const hubRaw = query.hub;
        if (hubRaw && typeof hubRaw === "object" && !Array.isArray(hubRaw)) {
            const hub = hubRaw;
            for (const key of ["mode", "verify_token", "challenge"]) {
                const value = this.asString(hub[key]);
                if (value &&
                    keys.some((candidate) => candidate.endsWith(key) || candidate === key)) {
                    return value;
                }
            }
        }
        return undefined;
    }
};
exports.MetaCloudWhatsappWebhookController = MetaCloudWhatsappWebhookController;
__decorate([
    (0, public_decorator_1.Public)(),
    (0, common_1.Get)(),
    openapi.ApiResponse({ status: 200 }),
    __param(0, (0, common_1.Query)()),
    __param(1, (0, common_1.Res)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Object]),
    __metadata("design:returntype", void 0)
], MetaCloudWhatsappWebhookController.prototype, "verifyWebhook", null);
__decorate([
    (0, public_decorator_1.Public)(),
    (0, common_1.Post)(),
    (0, common_1.HttpCode)(common_1.HttpStatus.OK),
    openapi.ApiResponse({ status: common_1.HttpStatus.OK }),
    __param(0, (0, common_1.Body)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], MetaCloudWhatsappWebhookController.prototype, "receiveWebhook", null);
exports.MetaCloudWhatsappWebhookController = MetaCloudWhatsappWebhookController = MetaCloudWhatsappWebhookController_1 = __decorate([
    (0, auth_decorator_1.Auth)(auth_type_enum_1.AuthType.None),
    (0, common_1.Controller)("webhook/whatsapp/meta-cloud"),
    (0, swagger_1.ApiTags)("Solid Core"),
    __metadata("design:paramtypes", [setting_service_1.SettingService])
], MetaCloudWhatsappWebhookController);
//# sourceMappingURL=meta-cloud-whatsapp-webhook.controller.js.map