import { Buff } from '@cmdcode/buff';
import { create_return_tx } from '../../lib/return.js';
import { get_deposit_ctx } from '../../lib/deposit.js';
import { create_covenant, create_return } from '../../lib/session.js';
export function register_utxo_api(client) {
    return async (account, utxo, txfee) => {
        const { agent_pk, sequence } = account;
        const pub = client.pubkey;
        const idx = Buff.hex(utxo.txid).slice(0, 4).num;
        const addr = client._wallet.get_account(idx).new_address();
        const ctx = get_deposit_ctx(agent_pk, pub, sequence);
        const rtx = create_return_tx(addr, ctx, client._signer, utxo, txfee);
        return rtx;
    };
}
export function commit_utxo_api(client) {
    return async (account, contract, utxo) => {
        const { agent_pk, sequence } = account;
        const pub = client.pubkey;
        const ctx = get_deposit_ctx(agent_pk, pub, sequence);
        return create_covenant(ctx, contract, client._signer, utxo);
    };
}
export function commit_deposit_api(client) {
    return async (contract, deposit) => {
        const { agent_pk, sequence, txid, vout, value, scriptkey } = deposit;
        const pub = client.pubkey;
        const ctx = get_deposit_ctx(agent_pk, pub, sequence);
        const utxo = { txid, vout, value, scriptkey };
        return create_covenant(ctx, contract, client._signer, utxo);
    };
}
export function commit_return_api(client) {
    return async (deposit, txfee, address) => {
        const { txid } = deposit;
        if (address === undefined) {
            const acct = Buff.hex(txid).slice(0, 4).num;
            address = client._wallet.get_account(acct).new_address();
        }
        return create_return(address, deposit, client._signer, txfee);
    };
}
export default function (client) {
    return {
        register_utxo: register_utxo_api(client),
        commit_utxo: commit_utxo_api(client),
        commit_deposit: commit_deposit_api(client),
        commit_return: commit_return_api(client)
    };
}
