var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
    if (kind === "m") throw new TypeError("Private method is not writable");
    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
    return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
};
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
    return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var _Manager_instances, _Manager_typegraph, _Manager_env, _Manager_getMigrationsDir, _Manager_serialize, _Manager_deploy, _Manager_list;
// Copyright Metatype OÜ, licensed under the Mozilla Public License Version 2.0.
// SPDX-License-Identifier: MPL-2.0
import "./_dnt.polyfills.js";
import { BasicAuth, tgDeploy } from "./tg_deploy.js";
import { freezeTgOutput } from "./utils/func_utils.js";
import { log, rpc } from "./io.js";
import { getCliEnv } from "./envs/cli.js";
import * as path from "path";
export class Manager {
    constructor(typegraph) {
        _Manager_instances.add(this);
        _Manager_typegraph.set(this, void 0);
        _Manager_env.set(this, void 0);
        __classPrivateFieldSet(this, _Manager_typegraph, typegraph, "f");
        __classPrivateFieldSet(this, _Manager_env, getCliEnv(), "f");
    }
    async run() {
        switch (__classPrivateFieldGet(this, _Manager_env, "f").command) {
            case "serialize":
                __classPrivateFieldGet(this, _Manager_instances, "m", _Manager_serialize).call(this);
                break;
            case "deploy":
                await __classPrivateFieldGet(this, _Manager_instances, "m", _Manager_deploy).call(this);
                break;
            case "list":
                __classPrivateFieldGet(this, _Manager_instances, "m", _Manager_list).call(this);
                break;
            default:
                throw new Error(`command ${__classPrivateFieldGet(this, _Manager_env, "f").command} from meta-cli not supported`);
        }
    }
}
_Manager_typegraph = new WeakMap(), _Manager_env = new WeakMap(), _Manager_instances = new WeakSet(), _Manager_getMigrationsDir = function _Manager_getMigrationsDir() {
    return path.join(__classPrivateFieldGet(this, _Manager_env, "f").migrations_dir, __classPrivateFieldGet(this, _Manager_typegraph, "f").name);
}, _Manager_serialize = function _Manager_serialize() {
    let finalizationResult;
    try {
        const env = __classPrivateFieldGet(this, _Manager_env, "f");
        finalizationResult = __classPrivateFieldGet(this, _Manager_typegraph, "f").serialize({
            typegraphPath: env.typegraph_path,
            prefix: env.prefix,
            artifactResolution: __classPrivateFieldGet(this, _Manager_env, "f").artifact_resolution,
            codegen: false,
            prismaMigration: {
                migrationsDir: __classPrivateFieldGet(this, _Manager_instances, "m", _Manager_getMigrationsDir).call(this),
                migrationActions: [],
                defaultMigrationAction: {
                    apply: true,
                    create: false,
                    reset: false,
                },
            },
            pretty: false,
        });
        log.success(finalizationResult.tgJson, true);
    }
    catch (err) {
        log.failure({
            typegraph: __classPrivateFieldGet(this, _Manager_typegraph, "f").name,
            errors: getErrorStack(err, "failed to serialize typegraph"),
        });
    }
}, _Manager_deploy = async function _Manager_deploy() {
    try {
        const deployData = await rpc.getDeployData(__classPrivateFieldGet(this, _Manager_typegraph, "f").name);
        const env = __classPrivateFieldGet(this, _Manager_env, "f");
        if (!env.artifact_resolution) {
            log.failure({
                typegraph: __classPrivateFieldGet(this, _Manager_typegraph, "f").name,
                errors: ["artifact resolution must be enabled for deployment"],
            });
            return;
        }
        const params = {
            typegraphPath: env.typegraph_path,
            prefix: env.prefix,
            artifactResolution: true,
            codegen: false,
            prismaMigration: {
                migrationsDir: __classPrivateFieldGet(this, _Manager_instances, "m", _Manager_getMigrationsDir).call(this),
                migrationActions: Object.entries(deployData.migrationActions),
                defaultMigrationAction: deployData.defaultMigrationAction,
            },
            pretty: false,
        };
        // hack for allowing tg.serialize(config) to be called more than once
        const frozenOut = freezeTgOutput(params, __classPrivateFieldGet(this, _Manager_typegraph, "f"));
        // hack for allowing tg.serialize(config) to be called more than once
        let frozenSerialized;
        try {
            frozenSerialized = frozenOut.serialize(params);
        }
        catch (err) {
            log.failure({
                typegraph: __classPrivateFieldGet(this, _Manager_typegraph, "f").name,
                errors: getErrorStack(err, "failed to serialize typegraph"),
            });
            return;
        }
        const reusableTgOutput = {
            ...__classPrivateFieldGet(this, _Manager_typegraph, "f"),
            serialize: () => frozenSerialized,
        };
        const deployTarget = await rpc.getDeployTarget();
        const { response, serialized } = await tgDeploy(reusableTgOutput, {
            typegate: {
                url: deployTarget.baseUrl,
                auth: new BasicAuth(deployTarget.auth.username, deployTarget.auth.password),
            },
            typegraphPath: env.typegraph_path,
            prefix: env.prefix,
            secrets: deployData.secrets,
            migrationsDir: __classPrivateFieldGet(this, _Manager_instances, "m", _Manager_getMigrationsDir).call(this),
            migrationActions: deployData.migrationActions,
            defaultMigrationAction: deployData.defaultMigrationAction,
        });
        log.success({
            typegraph: {
                name: __classPrivateFieldGet(this, _Manager_typegraph, "f").name,
                path: env.typegraph_path,
                value: serialized,
            },
            ...response,
        });
    }
    catch (err) {
        log.failure({
            typegraph: __classPrivateFieldGet(this, _Manager_typegraph, "f").name,
            errors: getErrorStack(err, "failed to deploy typegraph"),
        });
        return;
    }
}, _Manager_list = function _Manager_list() {
    log.success({ typegraph: __classPrivateFieldGet(this, _Manager_typegraph, "f").name });
};
// deno-lint-ignore no-explicit-any
function getErrorStack(err, defaultErr) {
    if (err instanceof Error) {
        log.debug(err);
        return [err.message];
    }
    return err?.stack ?? [err?.toString() ?? defaultErr];
}
