"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.sendCore = exports.send = void 0;
const tslib_1 = require("tslib");
const axios_1 = require("axios");
const helpers_1 = require("../helpers");
const constants_1 = require("../constants");
const helpers_2 = require("./helpers");
const conversationHash_1 = require("./conversationHash");
const helpers_3 = require("./helpers");
const messageObject_1 = require("../validations/messageObject");
const getGroupInfo_1 = require("./getGroupInfo");
/**
 * SENDS A PUSH CHAT MESSAGE
 */
const send = (options) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
    return yield (0, exports.sendCore)(options, helpers_2.PGPHelper);
});
exports.send = send;
const sendCore = (options, pgpHelper) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
    try {
        /**
         * Compute Input Options
         * 1. Provides the options object with default values
         * 2. Takes care of deprecated fields
         */
        const computedOptions = computeOptions(options);
        const { messageType, messageObj, account, to, signer, pgpPrivateKey, env } = computedOptions;
        /**
         * Validate Input Options
         */
        yield validateOptions(computedOptions);
        const wallet = (0, helpers_2.getWallet)({ account, signer });
        const sender = yield (0, helpers_2.getConnectedUserV2Core)(wallet, pgpPrivateKey, env, pgpHelper);
        const receiver = yield (0, helpers_2.getUserDID)(to, env);
        const API_BASE_URL = (0, helpers_1.getAPIBaseUrls)(env);
        const isGroup = (0, helpers_1.isValidETHAddress)(to) ? false : true;
        const group = isGroup
            ? yield (0, getGroupInfo_1.getGroupInfo)({
                chatId: to,
                env: env,
            })
            : null;
        // Not supported by legacy sdk versions, need to override messageContent to avoid parsing errors on legacy sdk versions
        let messageContent;
        if (messageType === constants_1.MessageType.REPLY ||
            messageType === constants_1.MessageType.COMPOSITE) {
            messageContent =
                'MessageType Not Supported by this sdk version. Plz upgrade !!!';
        }
        else {
            messageContent = messageObj.content;
        }
        const conversationResponse = yield (0, conversationHash_1.conversationHash)({
            conversationId: receiver,
            account: sender.did,
            env,
        });
        let apiEndpoint;
        if (!isGroup && conversationResponse && !(conversationResponse === null || conversationResponse === void 0 ? void 0 : conversationResponse.threadHash)) {
            apiEndpoint = `${API_BASE_URL}/v1/chat/request`;
        }
        else {
            apiEndpoint = `${API_BASE_URL}/v1/chat/message`;
        }
        const body = yield (0, helpers_3.sendMessagePayloadCore)(receiver, sender, messageObj, messageContent, messageType, group, env, pgpHelper);
        return (yield axios_1.default.post(apiEndpoint, body)).data;
    }
    catch (err) {
        console.error(`[Push SDK] - API  - Error - API ${exports.send.name} -:  `, err);
        throw Error(`[Push SDK] - API  - Error - API ${exports.send.name} -: ${err}`);
    }
});
exports.sendCore = sendCore;
const validateOptions = (options) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
    const { messageType, messageObj, account, to, signer, pgpPrivateKey, env } = options;
    if (!account && !signer) {
        throw new Error(`Unable to detect sender. Please ensure that either 'account' or 'signer' is properly defined.`);
    }
    if (!signer && !pgpPrivateKey) {
        throw new Error(`Unable to decrypt keys. Please ensure that either 'signer' or 'pgpPrivateKey' is properly defined.`);
    }
    const wallet = (0, helpers_2.getWallet)({ account, signer });
    const address = yield (0, helpers_2.getAccountAddress)(wallet);
    if (!(0, helpers_1.isValidETHAddress)(address)) {
        throw new Error(`Invalid sender. Please ensure that either 'account' or 'signer' is properly defined.`);
    }
    (0, messageObject_1.validateMessageObj)(messageObj, messageType);
});
const computeOptions = (options) => {
    var _a, _b, _c;
    const messageType = ((_a = options.message) === null || _a === void 0 ? void 0 : _a.type) !== undefined
        ? options.message.type
        : (_b = options.messageType) !== null && _b !== void 0 ? _b : 'Text';
    let messageObj = options.message;
    if (messageObj === undefined) {
        if (options.messageObj === undefined &&
            ![
                constants_1.MessageType.TEXT,
                constants_1.MessageType.IMAGE,
                constants_1.MessageType.FILE,
                constants_1.MessageType.MEDIA_EMBED,
                constants_1.MessageType.GIF,
            ].includes(messageType)) {
            throw new Error('Options.message is required');
        }
        else {
            messageObj =
                options.messageObj !== undefined
                    ? options.messageObj
                    : {
                        content: (_c = options.messageContent) !== null && _c !== void 0 ? _c : '',
                    };
        }
    }
    else {
        // Remove the 'type' property from messageObj
        const { type } = messageObj, rest = tslib_1.__rest(messageObj, ["type"]);
        messageObj = rest;
    }
    // Parse Reply Message
    if (messageType === constants_1.MessageType.REPLY) {
        if (typeof messageObj.content === 'object') {
            const _d = messageObj.content, { type } = _d, rest = tslib_1.__rest(_d, ["type"]);
            messageObj.content = {
                messageType: type,
                messageObj: rest,
            };
        }
        else {
            throw new Error('Options.message is not properly defined for Reply');
        }
    }
    // Parse Composite Message
    if (messageType === constants_1.MessageType.COMPOSITE) {
        if (messageObj.content instanceof Array) {
            messageObj.content = messageObj.content.map((obj) => {
                const { type } = obj, rest = tslib_1.__rest(obj, ["type"]);
                return {
                    messageType: type,
                    messageObj: rest,
                };
            });
        }
        else {
            throw new Error('Options.message is not properly defined for Composite');
        }
    }
    const account = options.account !== undefined ? options.account : null;
    const to = options.to !== undefined ? options.to : options.receiverAddress;
    if (to === undefined) {
        throw new Error('Options.to is required');
    }
    const signer = options.signer !== undefined ? options.signer : null;
    const pgpPrivateKey = options.pgpPrivateKey !== undefined ? options.pgpPrivateKey : null;
    const env = options.env !== undefined ? options.env : constants_1.default.ENV.PROD;
    return {
        messageType: messageType,
        messageObj: messageObj,
        account: account,
        to: to,
        signer: signer,
        pgpPrivateKey: pgpPrivateKey,
        env: env,
    };
};
//# sourceMappingURL=send.js.map