import { logger } from "../common/logger.js";
import settings from "../common/settings.js";
export class UnableToAutoLinkToExistingProject extends Error {
    constructor(projectName) {
        super(`Unable to link environment and system variables for ${projectName}. Check that the project specified in your zuplo.jsonc exists in your account.`);
        Object.setPrototypeOf(this, UnableToAutoLinkToExistingProject.prototype);
    }
}
export async function retrieveOrCreateEnvironment(branch, argv) {
    const environment = await retrieveFirstEnvironment(branch, argv);
    if (environment) {
        return environment;
    }
    else {
        return await createEnvironment(branch, argv);
    }
}
export async function retrieveFirstEnvironment(branch, argv) {
    const { account, project } = argv;
    const baseUrl = `${settings.ZUPLO_DEVELOPER_API_ENDPOINT}/v1/environments`;
    const queryParams = {
        accountName: account,
        projectName: project,
    };
    const url = new URL(baseUrl);
    url.search = new URLSearchParams(queryParams).toString();
    const readEnvironmentResponse = await fetch(url, {
        method: "GET",
        headers: {
            authorization: `Bearer ${argv.authToken}`,
        },
    });
    if (!readEnvironmentResponse.ok) {
        logger.debug(`Unable to auto-link environment and system variables for ${project} -- ${readEnvironmentResponse.status} ${readEnvironmentResponse.statusText}`);
        throw new UnableToAutoLinkToExistingProject(project);
    }
    const environmentJsonFromDeveloperAPI = (await readEnvironmentResponse.json());
    return environmentJsonFromDeveloperAPI.data.find((env) => env.branchName === branch);
}
export async function createEnvironment(branch, argv) {
    const { account, project } = argv;
    const baseUrl = `${settings.ZUPLO_DEVELOPER_API_ENDPOINT}/v1/environments`;
    let environmentType;
    if (branch === "main" || branch === "master" || branch === "production") {
        environmentType = "production";
    }
    else {
        environmentType = "preview";
    }
    const createEnvironmentResponse = await fetch(`${baseUrl}`, {
        method: "POST",
        headers: {
            authorization: `Bearer ${argv.authToken}`,
            "Content-Type": "application/json",
        },
        body: JSON.stringify({
            accountName: account,
            projectName: project,
            branchName: branch,
            environmentType,
        }),
    });
    if (createEnvironmentResponse.ok) {
        return await createEnvironmentResponse.json();
    }
    else {
        throw new Error(`Unable to create environment (project: ${project}, branch: ${branch}). Failed with ${createEnvironmentResponse.statusText}`);
    }
}
//# sourceMappingURL=environments.js.map