import { logger } from "../common/logger.js";
import { printCriticalFailureToConsoleAndExit, printDiagnosticsToConsole, printResultToConsoleAndExitGracefully, textOrJson, } from "../common/output.js";
import settings from "../common/settings.js";
import { normalizeUrl } from "../common/utils/urls.js";
export async function list(argv) {
    if (argv["self-hosted-endpoint"]) {
        const args = argv;
        await listFromSelfHosted(args);
    }
    else {
        await listFromSaas(argv);
    }
}
async function listFromSaas(argv) {
    const { account, project } = argv;
    const listResponse = await fetch(`${settings.ZUPLO_DEVELOPER_API_ENDPOINT}/v1/accounts/${account}/projects/${project}/deployments`, {
        method: "GET",
        headers: {
            Authorization: `Bearer ${argv.authToken}`,
        },
    });
    if (listResponse.ok) {
        const { data: deployments } = await listResponse.json();
        const output = deployments
            .filter((deployment) => deployment.url)
            .map((deployment) => deployment.url)
            .join("\n");
        await printResultToConsoleAndExitGracefully(output);
    }
    else {
        logger.error({
            status: listResponse.status,
            statusText: listResponse.statusText,
            response: textOrJson(await listResponse.text()),
        }, "Failed to list deployed zups");
        printDiagnosticsToConsole("Error: Failed to list deployed zups. Try again later.");
    }
}
async function listFromSelfHosted(argv) {
    const endpoint = normalizeUrl(argv["self-hosted-endpoint"]);
    const listResponse = await fetch(`${endpoint}/v1/deployments`, {
        method: "GET",
        headers: {
            Authorization: `Bearer ${argv.authToken}`,
        },
    });
    if (listResponse.ok) {
        const { data: deployments } = await listResponse.json();
        const output = deployments
            .map((deployment) => deployment.deploymentUrl)
            .join("\n");
        await printResultToConsoleAndExitGracefully(output);
    }
    else {
        logger.error(JSON.stringify(await listResponse.json(), null, 2), "Failed to list deployments at self-hosted build endpoint");
        await printCriticalFailureToConsoleAndExit("Error: Failed to list deployments at self-hosted build endpoint");
    }
}
//# sourceMappingURL=handler.js.map