import { Buff } from '@cmdcode/buff';
import { create_return_tx } from '../../lib/return.js';
import { get_deposit_ctx } from '../../lib/deposit.js';
import { verify_account } from '../../validators/deposit.js';
import { create_covenant, create_return } from '../../lib/session.js';
export function request_account_api(client) {
    return async (locktime) => {
        const pubkey = client.pubkey;
        return client.client.deposit.request({ pubkey, locktime });
    };
}
export function verify_account_api(signer) {
    return (account) => {
        const host_pub = signer.host_pub;
        const network = signer.client.network;
        if (host_pub === undefined) {
            throw new Error('host pubkey is not set on device');
        }
        verify_account(account, signer.pubkey, host_pub, network);
    };
}
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);
        return create_return_tx(addr, ctx, client._signer, utxo, txfee);
    };
}
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 close_deposit_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 {
        request_account: request_account_api(client),
        verify_account: verify_account_api(client),
        register_utxo: register_utxo_api(client),
        commit_utxo: commit_utxo_api(client),
        commit_deposit: commit_deposit_api(client),
        close_deposit: close_deposit_api(client)
    };
}
