import { readFile } from "node:fs/promises";
import { logger } from "../../../common/logger.js";
import { printCriticalFailureToConsoleAndExit, printDiagnosticsToConsole, printResultToConsoleAndExitGracefully, textOrJson, } from "../../../common/output.js";
import settings from "../../../common/settings.js";
import { pollProvisioningOperation } from "./poll-provisioning-operations.js";
export async function updateServices(argv) {
    let contents;
    try {
        contents = await readFile(argv["configuration-file"], "utf-8");
    }
    catch (err) {
        await printCriticalFailureToConsoleAndExit(`Error reading the configuration file at ${argv["configuration-file"]}: ${err.message}}`);
    }
    const { account } = argv;
    const deleteResponse = await fetch(`${settings.ZUPLO_DEVELOPER_API_ENDPOINT}/v1/accounts/${account}/tunnels/${argv["tunnel-id"]}/services-configuration`, {
        method: "PUT",
        headers: {
            Authorization: `Bearer ${argv.authToken}`,
            "Content-Type": "application/json",
        },
        body: contents,
    });
    if (deleteResponse.ok) {
        const provisioningOperation = await deleteResponse.json();
        printDiagnosticsToConsole(`Updating services on tunnel ${argv["tunnel-id"]} on account ${account}...`);
        const polledProvisioningOperation = await pollProvisioningOperation({
            argv,
            account,
            provisioningOperationId: provisioningOperation.id,
        });
        if (polledProvisioningOperation.status === "success") {
            await printResultToConsoleAndExitGracefully(`Tunnel ${argv["tunnel-id"]} updated successfully.`);
        }
        else {
            printDiagnosticsToConsole(polledProvisioningOperation.details);
            await printCriticalFailureToConsoleAndExit(`Tunnel ${argv["tunnel-id"]} failed to update. Here's the error: ${polledProvisioningOperation.message}`);
        }
    }
    else {
        const response = textOrJson(await deleteResponse.text());
        logger.error({
            status: deleteResponse.status,
            statusText: deleteResponse.statusText,
            response,
        }, "Failed to update tunnel for account");
        printDiagnosticsToConsole("Error: Failed to update the tunnel for your account. Check the arguments.", response);
    }
}
//# sourceMappingURL=handler.js.map