"use strict";
// SPDX-License-Identifier: Apache-2.0
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
require("../environmentMock");
const in_1 = require("../../../src/port/in");
const RegulationType_1 = require("../../../src/domain/context/factory/RegulationType");
const RPCTransactionAdapter_1 = require("../../../src/port/out/rpc/RPCTransactionAdapter");
const MirrorNodeAdapter_1 = require("../../../src/port/out/mirror/MirrorNodeAdapter");
const NetworkService_1 = __importDefault(require("../../../src/app/service/network/NetworkService"));
const RPCQueryAdapter_1 = require("../../../src/port/out/rpc/RPCQueryAdapter");
const config_1 = require("../../config");
const Injectable_1 = __importDefault(require("../../../src/core/injectable/Injectable"));
const Account_1 = __importDefault(require("../../../src/domain/context/account/Account"));
const ethers_1 = require("ethers");
const SsiManagement_1 = __importDefault(require("../../../src/port/in/ssiManagement/SsiManagement"));
const SecurityRole_1 = require("../../../src/domain/context/security/SecurityRole");
const verifiableCredentials_1 = __importDefault(require("../../utils/verifiableCredentials"));
const Terminal3_1 = require("../../../src/domain/context/kyc/Terminal3");
const HederaId_1 = require("../../../src/domain/context/shared/HederaId");
in_1.SDK.log = { level: "ERROR", transports: new in_1.LoggerTransports.Console() };
const decimals = 0;
const name = "TEST_SECURITY_TOKEN";
const symbol = "TEST";
const isin = "ABCDE123456Z";
const votingRight = true;
const informationRight = false;
const liquidationRight = true;
const subscriptionRight = false;
const conversionRight = true;
const redemptionRight = false;
const putRight = true;
const dividendRight = 1;
const currency = "0x345678";
const numberOfShares = 0;
const nominalValue = 1000;
const nominalValueDecimals = 3;
const regulationType = RegulationType_1.RegulationType.REG_D;
const regulationSubType = RegulationType_1.RegulationSubType.B_506;
const countries = "AF,HG,BN";
const info = "Anything";
const configId = "0x0000000000000000000000000000000000000000000000000000000000000000";
const configVersion = 1;
const mirrorNode = {
    name: "testmirrorNode",
    baseUrl: "https://testnet.mirrornode.hedera.com/api/v1/",
};
const rpcNode = {
    name: "testrpcNode",
    baseUrl: "http://127.0.0.1:7546/api",
};
let th;
let mirrorNodeAdapter;
describe("🧪 Kyc tests", () => {
    let ns;
    let rpcQueryAdapter;
    let equity;
    const url = "http://127.0.0.1:7546";
    const customHttpProvider = new ethers_1.ethers.JsonRpcProvider(url);
    beforeAll(async () => {
        try {
            mirrorNodeAdapter = Injectable_1.default.resolve(MirrorNodeAdapter_1.MirrorNodeAdapter);
            mirrorNodeAdapter.set(mirrorNode);
            th = Injectable_1.default.resolve(RPCTransactionAdapter_1.RPCTransactionAdapter);
            ns = Injectable_1.default.resolve(NetworkService_1.default);
            rpcQueryAdapter = Injectable_1.default.resolve(RPCQueryAdapter_1.RPCQueryAdapter);
            rpcQueryAdapter.init();
            ns.environment = "testnet";
            ns.configuration = {
                factoryAddress: config_1.FACTORY_ADDRESS,
                resolverAddress: config_1.RESOLVER_ADDRESS,
            };
            ns.mirrorNode = mirrorNode;
            ns.rpcNode = rpcNode;
            await th.init(true);
            const account = new Account_1.default({
                id: config_1.CLIENT_ACCOUNT_ECDSA.id.toString(),
                evmAddress: config_1.CLIENT_ACCOUNT_ECDSA.evmAddress,
                alias: config_1.CLIENT_ACCOUNT_ECDSA.alias,
                privateKey: config_1.CLIENT_ACCOUNT_ECDSA.privateKey,
                publicKey: config_1.CLIENT_ACCOUNT_ECDSA.publicKey,
            });
            await th.register(account, true);
            th.setSignerOrProvider(new ethers_1.Wallet(config_1.CLIENT_ACCOUNT_ECDSA.privateKey?.key ?? "", customHttpProvider));
            const requestST = new in_1.CreateEquityRequest({
                name,
                symbol,
                isin,
                decimals,
                isWhiteList: false,
                erc20VotesActivated: false,
                isControllable: true,
                arePartitionsProtected: false,
                clearingActive: false,
                internalKycActivated: true,
                isMultiPartition: false,
                diamondOwnerAccount: config_1.CLIENT_ACCOUNT_ECDSA.id.toString(),
                votingRight,
                informationRight,
                liquidationRight,
                subscriptionRight,
                conversionRight,
                redemptionRight,
                putRight,
                dividendRight,
                currency,
                numberOfShares: numberOfShares.toString(),
                nominalValue: nominalValue.toString(),
                nominalValueDecimals: nominalValueDecimals,
                regulationType: RegulationType_1.CastRegulationType.toNumber(regulationType),
                regulationSubType: RegulationType_1.CastRegulationSubType.toNumber(regulationSubType),
                isCountryControlListWhiteList: true,
                countries,
                info,
                configId,
                configVersion,
            });
            equity = (await in_1.Equity.create(requestST)).security;
        }
        catch (error) {
            console.error("Error in beforeAll setup:", error);
        }
        await in_1.Role.grantRole(new in_1.RoleRequest({
            securityId: equity.evmDiamondAddress,
            targetId: config_1.CLIENT_ACCOUNT_ECDSA.evmAddress.toString(),
            role: SecurityRole_1.SecurityRole._SSI_MANAGER_ROLE,
        }));
        await in_1.Role.grantRole(new in_1.RoleRequest({
            securityId: equity.evmDiamondAddress,
            targetId: config_1.CLIENT_ACCOUNT_ECDSA.evmAddress.toString(),
            role: SecurityRole_1.SecurityRole._KYC_ROLE,
        }));
        await SsiManagement_1.default.addIssuer(new in_1.AddIssuerRequest({
            securityId: equity.evmDiamondAddress,
            issuerId: config_1.CLIENT_EVM_ADDRESS_ECDSA_1_CORRECT,
        }));
    }, 900_000);
    it("Grant and revoke KYC", async () => {
        const vcBase64 = await (0, verifiableCredentials_1.default)(config_1.CLIENT_ACCOUNT_ECDSA_A.evmAddress.toString());
        expect((await in_1.Kyc.grantKyc(new in_1.GrantKycRequest({
            securityId: equity.evmDiamondAddress,
            targetId: config_1.CLIENT_ACCOUNT_ECDSA_A.evmAddress.toString(),
            vcBase64: vcBase64,
        }))).payload).toBe(true);
        let vcDecoded = Terminal3_1.Terminal3Vc.vcFromBase64(vcBase64);
        const issuer = Terminal3_1.Terminal3Vc.extractIssuer(vcDecoded);
        vcDecoded = Terminal3_1.Terminal3Vc.checkValidDates(vcDecoded);
        const issuerId = config_1.CLIENT_ACCOUNT_ECDSA.id.toString();
        const accountId = config_1.CLIENT_ACCOUNT_ECDSA_A.id.toString();
        // Override mock for this test to get issuer Id from EVM address
        jest
            .spyOn(mirrorNodeAdapter, "getAccountInfo")
            .mockResolvedValueOnce({ id: HederaId_1.HederaId.from(issuerId) })
            .mockResolvedValueOnce({ id: HederaId_1.HederaId.from(accountId) });
        expect(await in_1.Kyc.getKycAccountsData(new in_1.GetKycAccountsDataRequest({
            securityId: equity.evmDiamondAddress,
            kycStatus: 1,
            start: 0,
            end: 1,
        }))).toEqual([
            {
                account: config_1.CLIENT_ACCOUNT_ECDSA_A.id.toString(),
                validFrom: vcDecoded.validFrom?.substring(0, 10),
                validTo: vcDecoded.validUntil?.substring(0, 10),
                vcId: vcDecoded.id,
                issuer: config_1.CLIENT_ACCOUNT_ECDSA.id.toString(),
                status: 1,
            },
        ]);
        expect(await in_1.Kyc.getKycFor(new in_1.GetKycForRequest({
            securityId: equity.evmDiamondAddress,
            targetId: config_1.CLIENT_ACCOUNT_ECDSA_A.evmAddress.toString(),
        }))).toEqual({
            validFrom: vcDecoded.validFrom?.substring(0, 10),
            validTo: vcDecoded.validUntil?.substring(0, 10),
            vcId: vcDecoded.id,
            issuer: issuer,
            status: 1,
        });
        expect(await in_1.Kyc.getKycStatusFor(new in_1.GetKycStatusForRequest({
            securityId: equity.evmDiamondAddress,
            targetId: config_1.CLIENT_ACCOUNT_ECDSA_A.evmAddress.toString(),
        }))).toEqual(1);
        expect((await in_1.Kyc.revokeKyc(new in_1.RevokeKycRequest({
            securityId: equity.evmDiamondAddress,
            targetId: config_1.CLIENT_ACCOUNT_ECDSA_A.evmAddress.toString(),
        }))).payload).toBe(true);
        expect(await in_1.Kyc.getKycStatusFor(new in_1.GetKycStatusForRequest({
            securityId: equity.evmDiamondAddress,
            targetId: config_1.CLIENT_ACCOUNT_ECDSA_A.evmAddress.toString(),
        }))).toEqual(0);
        expect(await in_1.Kyc.getKycAccountsData(new in_1.GetKycAccountsDataRequest({
            securityId: equity.evmDiamondAddress,
            kycStatus: 1,
            start: 0,
            end: 1,
        }))).toEqual([]);
        expect(await in_1.Kyc.getKycAccountsCount(new in_1.GetKycAccountsCountRequest({
            securityId: equity.evmDiamondAddress,
            kycStatus: 1,
        }))).toEqual(0);
        expect((await SsiManagement_1.default.removeIssuer(new in_1.RemoveIssuerRequest({
            securityId: equity.evmDiamondAddress,
            issuerId: config_1.CLIENT_EVM_ADDRESS_ECDSA_1_CORRECT,
        }))).payload).toBe(true);
    }, 600_000);
    it("Cannot grant KYC with invalid VC", async () => {
        const invalidAddress = config_1.CLIENT_ACCOUNT_ECDSA.evmAddress;
        const vcBase64 = await (0, verifiableCredentials_1.default)(invalidAddress);
        await expect(async () => (await in_1.Kyc.grantKyc(new in_1.GrantKycRequest({
            securityId: equity.evmDiamondAddress,
            targetId: config_1.CLIENT_ACCOUNT_ECDSA_A.evmAddress.toString(),
            vcBase64: vcBase64,
        }))).payload).rejects.toThrow("The VC holder does not match target account");
    }, 600_000);
});
