"use strict";
// SPDX-License-Identifier: Apache-2.0
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 __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CustodialTransactionAdapter = void 0;
const sdk_1 = require("@hiero-ledger/sdk");
const hedera_custodians_integration_1 = require("@hashgraph/hedera-custodians-integration");
const Account_1 = __importDefault(require("../../../../domain/context/account/Account"));
const LazyInjectDecorator_1 = require("../../../../core/decorator/LazyInjectDecorator");
const EventService_1 = __importDefault(require("../../../../app/service/event/EventService"));
const MirrorNodeAdapter_1 = require("../../../out/mirror/MirrorNodeAdapter");
const NetworkService_1 = __importDefault(require("../../../../app/service/network/NetworkService"));
const LogService_1 = __importDefault(require("../../../../app/service/log/LogService"));
const SigningError_1 = require("../../../out/error/SigningError");
const WalletEvent_1 = require("../../../../app/service/event/WalletEvent");
const Injectable_1 = __importDefault(require("../../../../core/injectable/Injectable"));
const Hex_1 = __importDefault(require("../../../../core/Hex"));
const BaseHederaTransactionAdapter_1 = require("../../../out/hs/BaseHederaTransactionAdapter");
const HTSTransactionResponseAdapter_1 = require("../../../out/response/HTSTransactionResponseAdapter");
const HederaId_1 = require("../../../../domain/context/shared/HederaId");
const PublickKeyNotFound_1 = require("./error/PublickKeyNotFound");
const UnsupportedNetwork_1 = require("../../../../domain/context/network/error/UnsupportedNetwork");
let CustodialTransactionAdapter = class CustodialTransactionAdapter extends BaseHederaTransactionAdapter_1.BaseHederaTransactionAdapter {
    eventService;
    mirrorNodeAdapter;
    networkService;
    client;
    custodialWalletService;
    account;
    network;
    constructor(eventService, mirrorNodeAdapter, networkService) {
        super(mirrorNodeAdapter, networkService);
        this.eventService = eventService;
        this.mirrorNodeAdapter = mirrorNodeAdapter;
        this.networkService = networkService;
    }
    initClient(accountId, publicKey) {
        const currentNetwork = this.networkService.environment;
        switch (currentNetwork) {
            case "testnet":
                this.client = sdk_1.Client.forTestnet();
                break;
            case "mainnet":
                this.client = sdk_1.Client.forMainnet();
                break;
            case "previewnet":
                this.client = sdk_1.Client.forPreviewnet();
                break;
            default:
                throw new UnsupportedNetwork_1.UnsupportedNetwork();
        }
        this.client.setOperatorWith(accountId, publicKey, this.signingService);
    }
    signingService = async (message) => {
        const signatureRequest = new hedera_custodians_integration_1.SignatureRequest(message);
        return await this.custodialWalletService.signTransaction(signatureRequest);
    };
    async processTransaction(transaction, transactionType, 
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    _startDate) {
        try {
            const txResponse = await transaction.execute(this.client);
            this.logTransaction(txResponse.transactionId.toString(), this.networkService.environment);
            return HTSTransactionResponseAdapter_1.HTSTransactionResponseAdapter.manageResponse(this.networkService.environment, txResponse, transactionType, this.client);
        }
        catch (error) {
            LogService_1.default.logError(error);
            throw new SigningError_1.SigningError(error);
        }
    }
    supportsEvmOperations() {
        return false;
    }
    createWalletPairedEvent(wallet) {
        return {
            wallet: wallet,
            data: {
                account: this.account,
                pairing: "",
                topic: "",
            },
            network: {
                name: this.networkService.environment,
                recognized: true,
                factoryId: this.networkService.configuration?.factoryAddress ?? "",
            },
        };
    }
    async register(settings) {
        Injectable_1.default.registerTransactionHandler(this);
        const accountMirror = await this.mirrorNodeAdapter.getAccountInfo(new HederaId_1.HederaId(settings.hederaAccountId));
        if (!accountMirror.publicKey) {
            throw new PublickKeyNotFound_1.PublickKeyNotFound();
        }
        this.account = new Account_1.default({
            id: settings.hederaAccountId,
            evmAddress: accountMirror.evmAddress,
            publicKey: accountMirror.publicKey,
        });
        this.initCustodialWalletService(settings);
        this.initClient(settings.hederaAccountId, accountMirror.publicKey.key);
        const wallet = this.getSupportedWallet();
        const eventData = this.createWalletPairedEvent(wallet);
        this.eventService.emit(WalletEvent_1.WalletEvents.walletPaired, eventData);
        LogService_1.default.logTrace(`${wallet} registered as handler: `, eventData);
        return { account: this.getAccount() };
    }
    getAccount() {
        return this.account;
    }
    async sign(message) {
        if (!this.custodialWalletService)
            throw new SigningError_1.SigningError("Custodial Wallet is empty");
        try {
            const encoded_message = Hex_1.default.toUint8Array(message);
            const encoded_signed_message = await this.signingService(encoded_message);
            const hexArray = Array.from(encoded_signed_message, (byte) => ("0" + byte.toString(16)).slice(-2));
            return hexArray.join("");
        }
        catch (error) {
            LogService_1.default.logError(error);
            throw new SigningError_1.SigningError(error);
        }
    }
};
exports.CustodialTransactionAdapter = CustodialTransactionAdapter;
exports.CustodialTransactionAdapter = CustodialTransactionAdapter = __decorate([
    __param(0, (0, LazyInjectDecorator_1.lazyInject)(EventService_1.default)),
    __param(1, (0, LazyInjectDecorator_1.lazyInject)(MirrorNodeAdapter_1.MirrorNodeAdapter)),
    __param(2, (0, LazyInjectDecorator_1.lazyInject)(NetworkService_1.default)),
    __metadata("design:paramtypes", [EventService_1.default,
        MirrorNodeAdapter_1.MirrorNodeAdapter,
        NetworkService_1.default])
], CustodialTransactionAdapter);
