import { verify_endorsement } from '../../lib/member.js';
import { get_proposal_id } from '../../lib/proposal.js';
import { EscrowProposal } from '../../client/class/proposal.js';
import { validate_proposal, verify_proposal } from '../../validators/index.js';
import * as assert from '../../assert.js';
function create_contract_api(client) {
    return async (proposal, signatures) => {
        if (proposal instanceof EscrowProposal) {
            proposal = proposal.data;
        }
        validate_proposal(proposal);
        verify_proposal(proposal);
        if (signatures !== undefined) {
            const prop_id = get_proposal_id(proposal);
            signatures.forEach(e => verify_endorsement(prop_id, e, true));
        }
        const url = `${client.host}/api/contract/create`;
        const init = {
            body: JSON.stringify({ proposal, signatures }),
            method: 'POST',
            headers: { 'content-type': 'application/json' }
        };
        return client.fetcher({ url, init });
    };
}
function read_contract_api(client) {
    return async (cid) => {
        assert.is_hash(cid);
        const url = `${client.host}/api/contract/${cid}`;
        return client.fetcher({ url });
    };
}
function list_contract_api(client) {
    return async (token) => {
        const url = `${client.host}/api/contract/list`;
        return client.fetcher({ url, token });
    };
}
function list_funds_api(client) {
    return async (cid) => {
        assert.is_hash(cid);
        const url = `${client.host}/api/contract/${cid}/funds`;
        return client.fetcher({ url });
    };
}
function list_witness_api(client) {
    return async (cid) => {
        assert.is_hash(cid);
        const url = `${client.host}/api/contract/${cid}/witness`;
        return client.fetcher({ url });
    };
}
function submit_witness_api(client) {
    return async (cid, witness) => {
        assert.is_hash(cid);
        const url = `${client._host}/api/contract/${cid}/submit`;
        const init = {
            method: 'POST',
            body: JSON.stringify(witness),
            headers: { 'content-type': 'application/json' }
        };
        return client.fetcher({ url, init });
    };
}
export default function (client) {
    return {
        create: create_contract_api(client),
        funds: list_funds_api(client),
        list: list_contract_api(client),
        read: read_contract_api(client),
        submit: submit_witness_api(client),
        witness: list_witness_api(client)
    };
}
