import { request } from "@altangent/lib-http";
import qs from "querystring";
import { AddressOptions } from "./AddressOptions";
import { V2 } from "./ApiTypes";
import { BlockOptions } from "./BlockOptions";

export class BlockbookClient {
    constructor(readonly url: string) {}

    public async status(): Promise<V2.Status> {
        const path = `/api/v2`;
        return this.get(path);
    }

    public async blockhash(height: number): Promise<V2.BlockHash> {
        const path = `/api/v2/block-index/${height}`;
        return this.get(path);
    }

    public async tx(txid: string): Promise<V2.Tx> {
        const path = `/api/v2/tx/${txid}`;
        return this.get(path);
    }

    public async address(address: string, options: AddressOptions = {}): Promise<V2.AddressResult> {
        const query = qs.encode(options);
        const path = `/api/v2/address/${address}${query ? "?" + query : ""}`;
        return this.get(path);
    }

    public async block(
        heightOrHash: number | string,
        options: BlockOptions = {},
    ): Promise<V2.Block> {
        const query = qs.encode(options);
        const path = `/api/v2/block/${heightOrHash}${query ? "?" + query : ""}`;
        return this.get(path);
    }

    public async get<T>(path: string): Promise<T> {
        const url = `${this.url}${path}`;
        return (await request({ url, rejectUnauthorized: false })) as T;
    }
}
