/**
 * Monero send funds using monero-javascript
 * Creates a full wallet from keys, syncs, creates and relays transaction.
 * Compatible with createPspMoneroWallet() output (address, viewKey, spendKey).
 *
 * SECURITY: Run only locally. Never send spend_key to a remote server.
 */
'use strict';

const monerojs = require('monero-javascript');

const DEFAULT_DAEMON_URI = 'http://node.moneroworld.com:18081';
const DEFAULT_NETWORK = 'mainnet';

/**
 * Send XMR to a destination address.
 *
 * @param {string} address - Sender's Monero primary address
 * @param {string} viewKey - Sender's private view key (hex)
 * @param {string} spendKey - Sender's private spend key (hex)
 * @param {string} destination - Recipient's Monero address
 * @param {number|string} amountXmr - Amount in XMR (e.g. 0.5)
 * @param {object} options - Optional settings
 * @returns {Promise<{hash: string, fee: string}>}
 */
async function sendXmr(address, viewKey, spendKey, destination, amountXmr, options = {}) {
    const serverUri = options.serverUri || DEFAULT_DAEMON_URI;
    const networkType = options.networkType || DEFAULT_NETWORK;
    const restoreHeight = options.restoreHeight ?? 0;

    const amountAtomic = BigInt(Math.floor(parseFloat(amountXmr) * 1e12)).toString();

    let wallet = null;
    try {
        wallet = await monerojs.createWalletFull({
            path: '',
            password: '',
            networkType,
            primaryAddress: address,
            privateViewKey: viewKey,
            privateSpendKey: spendKey,
            restoreHeight,
            proxyToWorker: false,
            server: {
                uri: serverUri,
                username: options.serverUsername || '',
                password: options.serverPassword || ''
            }
        });

        await wallet.sync();

        const tx = await wallet.createTx({
            accountIndex: 0,
            address: destination,
            amount: amountAtomic,
            relay: true
        });

        const hash = tx.getHash();
        const fee = tx.getFee ? tx.getFee() : '0';

        return { hash: hash || 'relayed', fee: String(fee) };
    } finally {
        if (wallet) {
            try {
                await wallet.close(false);
            } catch (e) {
                console.warn('Wallet close:', e.message);
            }
        }
    }
}

module.exports = {
    sendXmr,
    DEFAULT_DAEMON_URI
};
