// Copyright Metatype OÜ, licensed under the Mozilla Public License Version 2.0.
// SPDX-License-Identifier: MPL-2.0
import "./_dnt.polyfills.js";
import { ArtifactUploader } from "./tg_artifact_upload.js";
import { wit_utils } from "./wit.js";
import { execRequest } from "./utils/func_utils.js";
import { log } from "./io.js";
export class BasicAuth {
    constructor(username, password) {
        Object.defineProperty(this, "username", {
            enumerable: true,
            configurable: true,
            writable: true,
            value: username
        });
        Object.defineProperty(this, "password", {
            enumerable: true,
            configurable: true,
            writable: true,
            value: password
        });
    }
    asHeaderValue() {
        return `Basic ${btoa(this.username + ":" + this.password)}`;
    }
}
export async function tgDeploy(typegraph, params) {
    const serializeParams = {
        typegraphPath: params.typegraphPath,
        prefix: params.prefix,
        artifactResolution: true,
        codegen: false,
        prismaMigration: {
            migrationsDir: params.migrationsDir ?? "prisma-migrations",
            migrationActions: Object.entries(params.migrationActions ?? {}),
            defaultMigrationAction: params.defaultMigrationAction ?? {
                apply: true,
                create: false,
                reset: false,
            },
        },
        pretty: false,
    };
    const serialized = typegraph.serialize(serializeParams);
    const tgJson = serialized.tgJson;
    const refArtifacts = serialized.ref_artifacts;
    const headers = new Headers();
    headers.append("Content-Type", "application/json");
    const typegate = params.typegate;
    if (typegate.auth) {
        headers.append("Authorization", typegate.auth.asHeaderValue());
    }
    const url = new URL("/typegate", typegate.url);
    // Make sure we have the correct credentials before doing anything
    await pingTypegate(url, headers);
    if (refArtifacts.length > 0) {
        // upload the artifacts
        const artifactUploader = new ArtifactUploader(typegate.url, refArtifacts, typegraph.name, typegate.auth, headers, params.typegraphPath);
        await artifactUploader.uploadArtifacts();
    }
    else {
        log.debug("no artifacts to upload");
    }
    // deploy the typegraph
    const response = (await execRequest(url, {
        method: "POST",
        headers,
        body: wit_utils.gqlDeployQuery({
            tg: tgJson,
            secrets: Object.entries(params.secrets ?? {}),
        }),
    }, `tgDeploy failed to deploy typegraph ${typegraph.name}`));
    if (response.errors) {
        for (const err of response.errors) {
            console.error(err.message);
        }
        throw new Error(`failed to deploy typegraph ${typegraph.name}`);
    }
    const addTypegraph = response.data.addTypegraph;
    /*
    // FIXME: failure field is used by interactive deployment
    // which means errors need to be ignored here but this
    // allows deployment errors in non-interactive scenarios
    if (addTypegraph.failure) {
      console.error(addTypegraph.failure);
      throw new Error(`failed to deploy typegraph ${typegraph.name}`);
    } */
    return {
        serialized: tgJson,
        response: addTypegraph,
    };
}
export async function tgRemove(typegraphName, params) {
    const { url, auth } = params.typegate;
    const headers = new Headers();
    headers.append("Content-Type", "application/json");
    if (auth) {
        headers.append("Authorization", auth.asHeaderValue());
    }
    const response = (await execRequest(new URL("/typegate", url), {
        method: "POST",
        headers,
        body: wit_utils.gqlRemoveQuery([typegraphName.toString()]),
    }, `tgRemove failed to remove typegraph ${typegraphName}`));
    return { typegate: response };
}
export async function pingTypegate(url, headers) {
    await execRequest(url, {
        method: "POST",
        headers,
        body: wit_utils.gqlPingQuery(),
    }, "Failed to access typegate");
}
