import { parse_deposit } from './parse.js';
import { get_return_script } from './return.js';
import { now, sort_record } from './util.js';
import { get_key_ctx, tweak_key_ctx } from '@cmdcode/musig2';
import { get_address, get_tapkey, parse_timelock } from './tx.js';
const GET_INIT_SPEND_STATE = () => {
    return {
        confirmed: false,
        block_hash: null,
        block_height: null,
        block_time: null,
        expires_at: null,
    };
};
const GET_INIT_DEPOSIT = () => {
    return {
        ...GET_INIT_SPEND_STATE(),
        covenant: null,
        created_at: now(),
        settled: false,
        settled_at: null,
        spent: false,
        spent_at: null,
        spent_txid: null
    };
};
export function create_deposit(template) {
    const deposit = { ...GET_INIT_DEPOSIT(), ...template };
    deposit.updated_at = deposit.created_at;
    if (deposit.confirmed) {
        deposit.status = (deposit.covenant !== null)
            ? 'locked'
            : 'open';
    }
    else {
        deposit.status = 'pending';
    }
    const parsed = parse_deposit(deposit);
    return sort_record(parsed);
}
export function get_deposit_ctx(agent_pk, member_pk, sequence) {
    const members = [member_pk, agent_pk];
    const script = get_return_script(member_pk, sequence);
    const int_data = get_key_ctx(members);
    const tap_data = get_tapkey(int_data.group_pubkey.hex, script);
    const key_data = tweak_key_ctx(int_data, [tap_data.taptweak]);
    return { agent_pk, member_pk, sequence, script, tap_data, key_data };
}
export function get_deposit_address(context, network) {
    const { tap_data } = context;
    return get_address(tap_data.tapkey, network);
}
export function get_spend_state(sequence, txstatus) {
    let state = GET_INIT_SPEND_STATE();
    if (txstatus !== undefined && txstatus.confirmed) {
        const timelock = parse_timelock(sequence);
        const expires_at = txstatus.block_time + timelock;
        state = { ...txstatus, expires_at };
    }
    return state;
}
