// Copyright Metatype OÜ, licensed under the Mozilla Public License Version 2.0.
// SPDX-License-Identifier: MPL-2.0
import { wit_utils } from "./wit.js";
export class BasicAuth {
    constructor(username, password) {
        this.username = username;
        this.password = password;
    }
    asHeaderValue() {
        return `Basic ${btoa(this.username + ":" + this.password)}`;
    }
}
export async function tgDeploy(typegraph, params) {
    const { baseUrl, cliVersion, secrets, auth, artifactsConfig } = params;
    const serialized = typegraph.serialize(artifactsConfig);
    const headers = new Headers();
    headers.append("Content-Type", "application/json");
    if (auth) {
        headers.append("Authorization", auth.asHeaderValue());
    }
    const response = await fetch(new URL("/typegate", baseUrl), {
        method: "POST",
        headers,
        body: wit_utils.gqlDeployQuery({
            cliVersion,
            tg: serialized,
            secrets: Object.entries(secrets !== null && secrets !== void 0 ? secrets : {}),
        }),
    });
    return {
        serialized,
        typegate: await handleResponse(response),
    };
}
export async function tgRemove(typegraph, params) {
    const { baseUrl, auth } = params;
    const headers = new Headers();
    headers.append("Content-Type", "application/json");
    if (auth) {
        headers.append("Authorization", auth.asHeaderValue());
    }
    const response = await fetch(new URL("/typegate", baseUrl), {
        method: "POST",
        headers,
        body: wit_utils.gqlRemoveQuery([typegraph.name]),
    });
    return {
        typegate: await handleResponse(response),
    };
}
async function handleResponse(response) {
    if (response.headers.get("Content-Type") == "application/json") {
        return await response.json();
    }
    return await response.text();
}
