"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 MetaCloudWhatsappService_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.MetaCloudWhatsappService = void 0;
const axios_1 = require("@nestjs/axios");
const common_1 = require("@nestjs/common");
const whatsapp_provider_decorator_1 = require("../../decorators/whatsapp-provider.decorator");
const setting_service_1 = require("../setting.service");
let MetaCloudWhatsappService = MetaCloudWhatsappService_1 = class MetaCloudWhatsappService {
    constructor(httpService, settingService) {
        this.httpService = httpService;
        this.settingService = settingService;
        this.logger = new common_1.Logger(MetaCloudWhatsappService_1.name);
    }
    async sendWhatsAppMessage(to, templateId, parameters, parentEntity, parentEntityId) {
        const message = {
            payload: {
                to,
                templateId,
                ...parameters,
            },
            parentEntity,
            parentEntityId,
        };
        await this.sendWhatsAppMessageSynchronously(message);
        return message;
    }
    async sendWhatsAppMessageSynchronously(message) {
        const phoneNumberId = this.settingService.getConfigValue("metaWhatsappPhoneNumberId");
        const apiVersion = this.settingService.getConfigValue("metaWhatsappApiVersion");
        const apiBaseUrl = this.settingService.getConfigValue("metaWhatsappApiUrl");
        const accessToken = this.settingService.getConfigValue("metaWhatsappAccessToken");
        if (!phoneNumberId || !apiVersion || !apiBaseUrl || !accessToken) {
            throw new Error("Missing Meta WhatsApp configuration. Set metaWhatsappApiUrl, metaWhatsappApiVersion, metaWhatsappPhoneNumberId, metaWhatsappAccessToken.");
        }
        const requestBody = this.createWhatsappRequest(message);
        const url = `${String(apiBaseUrl).replace(/\/$/, "")}/${apiVersion}/${phoneNumberId}/messages`;
        try {
            await this.httpService.axiosRef.post(url, requestBody, {
                headers: {
                    Authorization: `Bearer ${accessToken}`,
                    "Content-Type": "application/json",
                },
            });
            this.logger.debug(`Sent Meta WhatsApp message to ${message.payload?.to} with type ${requestBody.type}`);
        }
        catch (error) {
            const axiosError = error;
            const status = axiosError.response?.status;
            const data = axiosError.response?.data;
            this.logger.error(`Meta WhatsApp send failed: status=${status ?? "unknown"}, url=${url}, response=${typeof data === "object" ? JSON.stringify(data) : data}`);
            throw error;
        }
    }
    createWhatsappRequest(message) {
        const payload = message?.payload ?? {};
        if (payload?.payload) {
            const normalizedFromWrappedPayload = this.normalizeWrappedPayload(payload.payload);
            if (normalizedFromWrappedPayload) {
                return normalizedFromWrappedPayload;
            }
            return payload.payload;
        }
        const to = this.normalizePhone(payload.to);
        const templatePayload = payload;
        const textPayload = payload;
        if (textPayload.type === "text" || textPayload.text) {
            return {
                messaging_product: "whatsapp",
                recipient_type: "individual",
                to,
                type: "text",
                text: {
                    body: textPayload.text ?? "",
                    preview_url: Boolean(textPayload.previewUrl),
                },
            };
        }
        const templateName = payload.templateId || templatePayload.templateId || templatePayload.templateName;
        if (!templateName) {
            throw new Error("Meta WhatsApp template name is missing. Provide templateId or parameters.templateName.");
        }
        const components = [];
        if (templatePayload.headerText) {
            components.push({
                type: "header",
                parameters: [
                    {
                        type: "text",
                        text: templatePayload.headerText,
                    },
                ],
            });
        }
        else if (templatePayload.imageLink) {
            components.push({
                type: "header",
                parameters: [
                    {
                        type: "image",
                        image: { link: templatePayload.imageLink },
                    },
                ],
            });
        }
        if (Array.isArray(templatePayload.body) && templatePayload.body.length > 0) {
            components.push({
                type: "body",
                parameters: templatePayload.body.map((entry) => ({
                    type: "text",
                    text: String(entry),
                })),
            });
        }
        return {
            messaging_product: "whatsapp",
            recipient_type: "individual",
            to,
            type: "template",
            template: {
                name: templateName,
                language: {
                    code: templatePayload.languageCode || "en",
                },
                ...(components.length > 0 ? { components } : {}),
            },
        };
    }
    normalizeWrappedPayload(payload) {
        if (!payload || typeof payload !== "object") {
            return null;
        }
        if (payload.messaging_product && payload.to && payload.type) {
            return payload;
        }
        const destination = payload.destination || payload.to;
        const message = payload.message || {};
        if (!destination || !message.type) {
            return null;
        }
        if (message.type === "text" && message.text) {
            return {
                messaging_product: "whatsapp",
                recipient_type: "individual",
                to: this.normalizePhone(destination),
                type: "text",
                text: {
                    body: String(message.text),
                    preview_url: false,
                },
            };
        }
        if (message.type === "template" && message.template?.id) {
            const params = Array.isArray(message.template?.params)
                ? message.template.params
                : [];
            return {
                messaging_product: "whatsapp",
                recipient_type: "individual",
                to: this.normalizePhone(destination),
                type: "template",
                template: {
                    name: String(message.template.id),
                    language: {
                        code: "en",
                    },
                    ...(params.length > 0
                        ? {
                            components: [
                                {
                                    type: "body",
                                    parameters: params.map((entry) => ({
                                        type: "text",
                                        text: String(entry),
                                    })),
                                },
                            ],
                        }
                        : {}),
                },
            };
        }
        return null;
    }
    normalizePhone(phone) {
        const digits = String(phone || "").replace(/\D/g, "");
        if (!digits) {
            throw new Error("Destination phone number is required for WhatsApp message.");
        }
        return digits;
    }
};
exports.MetaCloudWhatsappService = MetaCloudWhatsappService;
exports.MetaCloudWhatsappService = MetaCloudWhatsappService = MetaCloudWhatsappService_1 = __decorate([
    (0, common_1.Injectable)(),
    (0, whatsapp_provider_decorator_1.WhatsAppProvider)(),
    __metadata("design:paramtypes", [axios_1.HttpService,
        setting_service_1.SettingService])
], MetaCloudWhatsappService);
//# sourceMappingURL=MetaCloudWhatsappService.js.map