import { createClient } from "../util/api/client/client.gen.js";
import { createConfig } from "../util/api/client/utils.gen.js";
import { ClickhouseClient } from "./api/sdk.gen.js";
export class ClickhouseError extends Error {
    status;
    method;
    url;
    code;
    constructor(props) {
        const { status, error } = props.error;
        super(`A request to the Clickhouse API failed (${props.response.status}): ${error}`);
        this.status = props.response.status;
        this.method = props.request.method;
        this.url = props.request.url;
        this.code = status?.toString() ?? "";
        Object.assign(this, props.error);
    }
}
/**
 * Create a ClickhouseApi instance with environment variable fallback
 * @param options API options
 * @returns ClickhouseApi instance
 */
export function createClickhouseApi(options = {}) {
    const keyId = options?.keyId ?? process.env.CLICKHOUSE_KEY_ID;
    const secret = options?.secret ?? process.env.CLICKHOUSE_KEY_SECRET;
    const client = createClient(createConfig({
        baseUrl: "https://api.clickhouse.cloud",
        throwOnError: true,
        headers: {
            Authorization: `Basic ${btoa(`${keyId}:${secret}`)}`,
        },
    }));
    client.interceptors.error.use((error, response, request, options) => {
        if (options.throwOnError !== false) {
            throw new ClickhouseError({
                error: error,
                request,
                response,
            });
        }
        return error;
    });
    return new ClickhouseClient({
        client,
    });
}
//# sourceMappingURL=api.js.map