"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.unsubscribeV2 = void 0;
const tslib_1 = require("tslib");
const axios_1 = require("axios");
const helpers_1 = require("../helpers");
const signature_helpers_1 = require("./signature.helpers");
const constants_1 = require("../constants");
const unsubscribeV2 = (options) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
    var _a, _b;
    const { signer, channelAddress, userAddress, verifyingContractAddress, env = constants_1.default.ENV.PROD, onSuccess, onError, } = options || {};
    try {
        const _channelAddress = yield (0, helpers_1.getCAIPAddress)(env, channelAddress, 'Channel');
        const channelCAIPDetails = (0, helpers_1.getCAIPDetails)(_channelAddress);
        if (!channelCAIPDetails)
            throw Error('Invalid Channel CAIP!');
        const chainId = parseInt(channelCAIPDetails.networkId, 10);
        const _userAddress = yield (0, helpers_1.getCAIPAddress)(env, userAddress, 'User');
        const userCAIPDetails = (0, helpers_1.getCAIPDetails)(_userAddress);
        if (!userCAIPDetails)
            throw Error('Invalid User CAIP!');
        const { API_BASE_URL, EPNS_COMMUNICATOR_CONTRACT } = (0, helpers_1.getConfig)(env, channelCAIPDetails);
        const requestUrl = `${API_BASE_URL}/v1/channels/${_channelAddress}/unsubscribe`;
        // get domain information
        const domainInformation = (0, signature_helpers_1.getDomainInformation)(chainId, verifyingContractAddress || EPNS_COMMUNICATOR_CONTRACT);
        // get type information
        const typeInformation = (0, signature_helpers_1.getTypeInformationV2)();
        // get message
        const messageInformation = {
            data: (0, signature_helpers_1.getSubscriptionMessageV2)(channelCAIPDetails.address, userCAIPDetails.address, 'Unsubscribe'),
        };
        // sign a message using EIP712
        const pushSigner = new helpers_1.Signer(signer);
        const signature = yield pushSigner.signTypedData(domainInformation, typeInformation, messageInformation, 'Data');
        const verificationProof = signature; // might change
        const body = {
            verificationProof: `eip712v2:${verificationProof}`,
            message: messageInformation.data,
        };
        const res = yield axios_1.default.post(requestUrl, body);
        if (typeof onSuccess === 'function')
            onSuccess();
        return { status: res.status, message: 'successfully opted out channel' };
    }
    catch (err) {
        if (typeof onError === 'function')
            onError(err);
        return {
            status: (_b = (_a = err === null || err === void 0 ? void 0 : err.response) === null || _a === void 0 ? void 0 : _a.status) !== null && _b !== void 0 ? _b : '',
            message: err instanceof Error ? err.message : JSON.stringify(err),
        };
    }
});
exports.unsubscribeV2 = unsubscribeV2;
//# sourceMappingURL=unsubscribeV2.js.map