import { parse_extkey } from '@cmdcode/crypto-tools/hd';
import { get_deposit_ctx } from '../../../lib/deposit.js';
import { verify_account } from '../../../client/validators/deposit.js';
import { create_covenant, create_return_psig } from '../../../lib/session.js';
export function create_account_api(signer) {
    return (locktime, index) => {
        index = index ?? signer._gen_idx();
        const deposit_pk = signer.pubkey;
        const spend_xpub = signer.wallet.get(index).xpub;
        return { deposit_pk, locktime, spend_xpub };
    };
}
export function verify_account_api(signer) {
    return (account) => {
        try {
            verify_account(account, signer);
            return true;
        }
        catch (err) {
            return false;
        }
    };
}
export function commit_funds_api(signer) {
    return (account, contract, utxo) => {
        const { agent_pk, sequence, spend_xpub } = account;
        if (!signer.wallet.has(spend_xpub)) {
            throw new Error('account xpub is not recognized by master wallet');
        }
        const deposit_pk = signer.pubkey;
        const return_pk = parse_extkey(spend_xpub).pubkey;
        const ctx = get_deposit_ctx(agent_pk, deposit_pk, return_pk, sequence);
        const covenant = create_covenant(ctx, contract, signer._signer, utxo);
        return { covenant, deposit_pk, sequence, spend_xpub, utxo };
    };
}
export function lock_funds_api(signer) {
    return (contract, deposit) => {
        const { agent_pk, sequence, txid, vout, value, scriptkey, spend_xpub } = deposit;
        if (!signer.wallet.has(spend_xpub)) {
            throw new Error('account xpub is not recognized by master wallet');
        }
        const deposit_pk = signer.pubkey;
        const return_pk = parse_extkey(spend_xpub).pubkey;
        const ctx = get_deposit_ctx(agent_pk, deposit_pk, return_pk, sequence);
        const utxo = { txid, vout, value, scriptkey };
        const covenant = create_covenant(ctx, contract, signer._signer, utxo);
        return { covenant };
    };
}
export function close_account_api(signer) {
    return (deposit, txfee) => {
        const [pnonce, psig] = create_return_psig(deposit, signer._signer, txfee);
        return { pnonce, psig, txfee };
    };
}
export default function (signer) {
    return {
        create: create_account_api(signer),
        verify: verify_account_api(signer),
        close: close_account_api(signer),
        commit: commit_funds_api(signer),
        lock: lock_funds_api(signer)
    };
}
