"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.approveCore = exports.approve = 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 CryptoJS = require("crypto-js");
const AES = require("../chat/helpers/aes");
const getGroupInfo_1 = require("./getGroupInfo");
const getAllGroupMembersPublicKeys_1 = require("./getAllGroupMembersPublicKeys");
const config_1 = require("../config");
/**
 * Approve Chat Request
 */
const approve = (options) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
    return yield (0, exports.approveCore)(options, helpers_2.PGPHelper);
});
exports.approve = approve;
const approveCore = (options, pgpHelper) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
    const { status = 'Approved', account = null, signer = null, senderAddress, env = constants_1.default.ENV.PROD, pgpPrivateKey = null, overrideSecretKeyGeneration = !config_1.ALPHA_FEATURE_CONFIG[constants_1.PACKAGE_BUILD].feature.includes(constants_1.default.ALPHA_FEATURES.SCALABILITY_V2), } = options || {};
    /**
     * VALIDATIONS
     */
    if (account == null && signer == null) {
        throw new Error(`At least one from account or signer is necessary!`);
    }
    /**
     * INITIALIZATIONS
     */
    const wallet = (0, helpers_2.getWallet)({ account, signer });
    const address = yield (0, helpers_2.getAccountAddress)(wallet);
    const isGroup = !(0, helpers_1.isValidETHAddress)(senderAddress);
    const connectedUser = yield (0, helpers_2.getConnectedUserV2Core)(wallet, pgpPrivateKey, env, pgpHelper);
    const fromDID = isGroup
        ? yield (0, helpers_2.getUserDID)(address, env)
        : yield (0, helpers_2.getUserDID)(senderAddress, env);
    const toDID = isGroup
        ? yield (0, helpers_2.getUserDID)(senderAddress, env)
        : yield (0, helpers_2.getUserDID)(address, env);
    let encryptedSecret = null;
    /**
     * GENERATE VERIFICATION PROOF
     */
    // pgp is used for public grps & w2w
    // pgpv2 is used for private grps
    let sigType = 'pgp';
    if (isGroup) {
        const group = yield (0, getGroupInfo_1.getGroupInfo)({ chatId: senderAddress, env });
        if (group && !group.isPublic) {
            /**
             * Secret Key Gen Override has no effect if an encrypted secret key is already present
             */
            if (group.encryptedSecret || !overrideSecretKeyGeneration) {
                sigType = 'pgpv2';
                const secretKey = AES.generateRandomSecret(15);
                const groupMembers = yield (0, getAllGroupMembersPublicKeys_1.getAllGroupMembersPublicKeys)({
                    chatId: group.chatId,
                    env,
                });
                // Encrypt secret key with group members public keys
                const publicKeys = groupMembers.map((member) => member.publicKey);
                publicKeys.push(connectedUser.publicKey);
                encryptedSecret = yield pgpHelper.pgpEncrypt({
                    plainText: secretKey,
                    keys: publicKeys,
                });
            }
        }
    }
    let bodyToBeHashed;
    switch (sigType) {
        case 'pgp': {
            bodyToBeHashed = {
                fromDID,
                toDID,
                status,
            };
            break;
        }
        case 'pgpv2': {
            bodyToBeHashed = {
                fromDID,
                toDID,
                status,
                encryptedSecret: encryptedSecret,
            };
            break;
        }
    }
    const hash = CryptoJS.SHA256(JSON.stringify(bodyToBeHashed)).toString();
    const signature = yield pgpHelper.sign({
        message: hash,
        signingKey: connectedUser.privateKey,
    });
    const verificationProof = `${sigType}:${signature}`;
    const body = {
        fromDID,
        toDID,
        signature,
        status,
        sigType,
        verificationProof,
        encryptedSecret,
    };
    /**
     * API CALL TO PUSH NODES
     */
    const API_BASE_URL = (0, helpers_1.getAPIBaseUrls)(env);
    const apiEndpoint = `${API_BASE_URL}/v1/chat/request/accept`;
    return axios_1.default
        .put(apiEndpoint, body)
        .then((response) => {
        return response.data;
    })
        .catch((err) => {
        console.error(`[Push SDK] - API ${exports.approve.name}: `, err);
        throw Error(`[Push SDK] - API ${exports.approve.name}: ${err}`);
    });
});
exports.approveCore = approveCore;
//# sourceMappingURL=approveRequest.js.map