import { createClient, createConfig, } from "../util/api/client/index.js";
import { PlanetScaleClient } from "./api/sdk.gen.js";
export class PlanetScaleError extends Error {
    status;
    method;
    url;
    code;
    constructor(props) {
        super(`A request to the PlanetScale API failed (${props.response.status}: ${props.error.message}`);
        this.status = props.response.status;
        this.method = props.request.method;
        this.url = props.request.url;
        this.code = props.error.code;
    }
}
export function createPlanetScaleClient(options = {}) {
    const token = extractToken(options);
    const client = createClient(createConfig({
        baseUrl: options.baseUrl ?? "https://api.planetscale.com/v1",
        headers: {
            Authorization: token, // PlanetScale does not use the Bearer prefix
        },
        throwOnError: true,
    }));
    client.interceptors.error.use((error, response, request) => {
        return new PlanetScaleError({
            error: error,
            request,
            response,
        });
    });
    return new PlanetScaleClient({
        client,
    });
}
export const extractToken = (props) => {
    if (props.apiKey) {
        return props.apiKey.unencrypted;
    }
    else if (props.serviceTokenId && props.serviceToken) {
        return `${props.serviceTokenId.unencrypted}:${props.serviceToken.unencrypted}`;
    }
    else if (process.env.PLANETSCALE_API_TOKEN) {
        return process.env.PLANETSCALE_API_TOKEN;
    }
    else if (process.env.PLANETSCALE_SERVICE_TOKEN_ID &&
        process.env.PLANETSCALE_SERVICE_TOKEN) {
        return `${process.env.PLANETSCALE_SERVICE_TOKEN_ID}:${process.env.PLANETSCALE_SERVICE_TOKEN}`;
    }
    else {
        throw new Error("No authentication token provided for PlanetScale. Please provide an API key, service token ID and secret, or set the PLANETSCALE_SERVICE_TOKEN_ID and PLANETSCALE_SERVICE_TOKEN environment variables.");
    }
};
//# sourceMappingURL=api.js.map