"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.WalletService = void 0;
const ethers_1 = require("ethers");
const tronweb_1 = require("tronweb");
const PaymentWalletModel_js_1 = require("../database/models/PaymentWalletModel.js");
class WalletService {
    cryptoBox;
    constructor(cryptoBox) {
        this.cryptoBox = cryptoBox;
    }
    async getOrCreateWallet(telegramId, network) {
        const existing = await PaymentWalletModel_js_1.PaymentWalletModel.findOne({ telegramId, network });
        if (existing)
            return existing;
        const generated = network === "tron" ? await this.generateTronWallet() : this.generateEvmWallet();
        return PaymentWalletModel_js_1.PaymentWalletModel.create({
            telegramId,
            network,
            walletAddress: generated.address,
            encryptedPrivateKey: this.cryptoBox.encrypt(generated.privateKey),
            keyReference: "local:aes-256-gcm"
        });
    }
    async getPrivateKey(telegramId, network) {
        const wallet = await PaymentWalletModel_js_1.PaymentWalletModel.findOne({ telegramId, network });
        if (!wallet)
            return null;
        return this.cryptoBox.decrypt(wallet.encryptedPrivateKey);
    }
    generateEvmWallet() {
        const wallet = ethers_1.ethers.Wallet.createRandom();
        return { address: wallet.address, privateKey: wallet.privateKey };
    }
    async generateTronWallet() {
        const account = await tronweb_1.TronWeb.createAccount();
        return { address: account.address.base58, privateKey: account.privateKey };
    }
}
exports.WalletService = WalletService;
