import { normalize } from "node:path";
import { logger } from "../common/logger.js";
import { printCriticalFailureToConsoleAndExit, printResultToConsoleAndExitGracefully, } from "../common/output.js";
import settings from "../common/settings.js";
import { pingDeployment } from "./poll-deployment.js";
export async function deleteZup(argv) {
    if (argv["self-hosted-endpoint"]) {
        const args = argv;
        await deleteFromSelfHosted(args);
    }
    else {
        await deleteFromSaas(argv);
    }
}
async function deleteFromSaas(argv) {
    let deploymentName;
    try {
        deploymentName = await checkUrl(argv, deploymentName);
    }
    catch (err) {
        logger.error(err, "Failed to parse the URL");
        await printCriticalFailureToConsoleAndExit(`Error: Failed to parse the URL: ${argv.url}. Ensure you have entered a valid URL.`);
    }
    const { account, project } = argv;
    const deleteResponse = await fetch(`${settings.ZUPLO_DEVELOPER_API_ENDPOINT}/v1/accounts/${account}/projects/${project}/deployments/${deploymentName}`, {
        method: "DELETE",
        headers: {
            Authorization: `Bearer ${argv.authToken}`,
        },
    });
    if (deleteResponse.ok) {
        if (argv.wait) {
            const deleted = await pingDeployment(argv);
            if (!deleted) {
                logger.error(`Failed to confirm deletion of zup within alloted time frame.`);
                await printCriticalFailureToConsoleAndExit(`Error: Failed to confirm deletion of zup within alloted time frame of ${settings.MAX_POLL_RETRIES * settings.POLL_INTERVAL} ms. Your zup is still be available at ${argv.url}.`);
            }
            else {
                await printResultToConsoleAndExitGracefully(`Deleted ${argv.url}`);
            }
        }
        else {
            await printResultToConsoleAndExitGracefully(`Enqueued deletion of ${argv.url}`);
        }
    }
    else {
        logger.error({
            status: deleteResponse.status,
            statusText: deleteResponse.statusText,
        }, "Failed to enqueue the deletion request");
        await printCriticalFailureToConsoleAndExit("Error: Failed to enqueue the deletion request. Try again later.");
    }
}
async function deleteFromSelfHosted(argv) {
    let deploymentName;
    try {
        deploymentName = await checkUrl(argv, deploymentName);
    }
    catch (err) {
        logger.error(err, "Failed to parse the URL");
        await printCriticalFailureToConsoleAndExit(`Error: Failed to parse the URL: ${argv.url}. Ensure you have entered a valid URL.`);
    }
    const endpoint = normalize(argv["self-hosted-endpoint"]);
    const deleteResponse = await fetch(`${endpoint}/v1/deployments/${deploymentName}`, {
        method: "DELETE",
        headers: {
            Authorization: `Bearer ${argv.authToken}`,
        },
    });
    if (deleteResponse.ok) {
        await printResultToConsoleAndExitGracefully(`Enqueued deletion of ${argv.url}`);
    }
    else {
        logger.error(JSON.stringify(await deleteResponse.json(), null, 2), "Failed to upload to self-hosted build endpoint");
        await printCriticalFailureToConsoleAndExit("Error: Failed to enqueue the deletion request. Try again later.");
    }
}
async function checkUrl(argv, deploymentName) {
    let url = argv.url;
    if (!/^(http:\/\/|https:\/\/)/i.test(argv.url)) {
        url = "https://" + url;
    }
    const parsedUrl = new URL(url);
    if (parsedUrl.username || parsedUrl.password) {
        logger.error(`Extra username and/or password was included in the URL.`);
        await printCriticalFailureToConsoleAndExit(`Error: Extraneous username and/or password in the URL. Only include the hostname.`);
    }
    if (parsedUrl.pathname !== "/") {
        logger.error(`Extra pathname was included in the URL: ${parsedUrl.pathname}`);
        await printCriticalFailureToConsoleAndExit(`Error: Extraneous pathname in URL: ${parsedUrl.pathname}. Only include the hostname.`);
    }
    if (parsedUrl.search !== "") {
        logger.error(`Extra search params were included in the URL: ${parsedUrl.search}`);
        await printCriticalFailureToConsoleAndExit(`Error: Extraneous search params in URL: ${parsedUrl.search}. Only include the hostname.`);
    }
    deploymentName = parsedUrl.hostname.split(".")[0];
    return deploymentName;
}
//# sourceMappingURL=handler.js.map