import { createApiClient } from "../../common/api/client.js";
import { logger } from "../../common/logger.js";
import { printCriticalFailureToConsoleAndExit, printJsonToConsoleAndExitGracefully, printResultToConsoleAndExitGracefully, } from "../../common/output.js";
async function resolveDeploymentName(customDomain) {
    if (customDomain.deployments.length === 0) {
        return undefined;
    }
    if (customDomain.deployments.length === 1) {
        return customDomain.deployments[0].deploymentName ?? undefined;
    }
    logger.error({
        hostname: customDomain.hostname,
        deploymentCount: customDomain.deployments.length,
    }, "Custom domain deletion requires an explicit deployment name");
    await printCriticalFailureToConsoleAndExit(`Error: Custom domain ${customDomain.hostname} is assigned to multiple deployments. Rerun with --deployment-name.`);
    throw new Error("printCriticalFailureToConsoleAndExit returned unexpectedly");
}
async function inferDeploymentName(argv) {
    if (argv["deployment-name"]) {
        return argv["deployment-name"];
    }
    const client = createApiClient({ authToken: argv.authToken });
    const customDomains = await client.get(`/v1/accounts/${argv.account}/custom-domains`, {
        operation: "Failed to fetch custom domains for deletion preflight",
        errorMessage: "Error: Failed to look up custom domain assignments before deletion. Try again with --deployment-name.",
    });
    const matchingCustomDomain = customDomains.data.find((customDomain) => {
        return customDomain.hostname === argv.hostname;
    });
    if (!matchingCustomDomain) {
        return undefined;
    }
    return resolveDeploymentName(matchingCustomDomain);
}
export async function deleteCustomDomain(argv) {
    const { account, hostname } = argv;
    const deploymentName = await inferDeploymentName(argv);
    const query = new URLSearchParams();
    query.set("hostname", hostname);
    if (deploymentName) {
        query.set("deploymentName", deploymentName);
    }
    const client = createApiClient({ authToken: argv.authToken });
    await client.delete(`/v1/accounts/${account}/custom-domains?${query.toString()}`, {
        operation: "Failed to delete custom domain for account",
        errorMessage: "Error: Failed to delete custom domain for your account. Check the arguments.",
        emptyResponse: true,
    });
    if (argv.output === "json") {
        await printJsonToConsoleAndExitGracefully({
            deleted: true,
            hostname,
            deploymentName: deploymentName ?? null,
        });
    }
    else {
        await printResultToConsoleAndExitGracefully(`Custom domain ${hostname} deleted successfully.`);
    }
}
//# sourceMappingURL=handler.js.map