import { createClient } from "../util/api/client/client.gen.js";
import { createConfig } from "../util/api/client/utils.gen.js";
import { NeonClient } from "./api/sdk.gen.js";
export class NeonError extends Error {
    status;
    method;
    url;
    code;
    constructor(props) {
        const { code, message, ...rest } = props.error;
        super(`A request to the Neon API failed (${props.response.status}): ${message}`);
        this.status = props.response.status;
        this.method = props.request.method;
        this.url = props.request.url;
        this.code = code;
        Object.assign(this, rest);
    }
}
/**
 * Create a NeonApi instance with environment variable fallback
 * @param options API options
 * @returns NeonApi instance
 */
export function createNeonApi(options = {}) {
    const apiKey = options.apiKey?.unencrypted ?? process.env.NEON_API_KEY;
    if (!apiKey) {
        throw new Error("Neon API key is required. Set NEON_API_KEY environment variable or provide apiKey option.");
    }
    const client = createClient(createConfig({
        baseUrl: options.baseUrl ?? "https://console.neon.tech/api/v2",
        throwOnError: true,
        headers: {
            Authorization: `Bearer ${apiKey}`,
        },
    }));
    client.interceptors.error.use((error, response, request, options) => {
        if (options.throwOnError !== false) {
            throw new NeonError({
                error: error,
                request,
                response,
            });
        }
        return error;
    });
    return new NeonClient({
        client,
    });
}
//# sourceMappingURL=api.js.map