import { logger } from "../../../common/logger.js";
import { printDiagnosticsToConsole, textOrJson, } from "../../../common/output.js";
import settings from "../../../common/settings.js";
function wait(duration = settings.PROVISIONING_POLL_INTERVAL) {
    return new Promise((resolve) => setTimeout(resolve, duration));
}
export async function pollProvisioningOperation(args) {
    const authToken = args.argv.authToken;
    const tunnelId = args.argv["tunnel-id"];
    for (let pollRetry = 0; pollRetry < settings.MAX_PROVISIONING_RETRIES; pollRetry++) {
        printDiagnosticsToConsole(`Polling for provisioning operation status... (${pollRetry}/${settings.MAX_PROVISIONING_RETRIES})`);
        const response = await fetch(`${settings.ZUPLO_DEVELOPER_API_ENDPOINT}/v1/accounts/${args.account}/tunnels/${tunnelId}/provisioning-operations/${args.provisioningOperationId}`, {
            method: "GET",
            headers: {
                Authorization: `Bearer ${authToken}`,
            },
        });
        if (response.ok) {
            const provisioningOperation = await response.json();
            switch (provisioningOperation.status) {
                case "error":
                    return provisioningOperation;
                case "in-progress":
                    await wait();
                    continue;
                case "success":
                    return provisioningOperation;
            }
        }
        else {
            logger.error({
                status: response.status,
                statusText: response.statusText,
                response: textOrJson(await response.text()),
            }, "Unexpected error from server while polling for provisioning operation status");
            throw new Error(`Unexpected response from server while polling for provisioning operation status: ${response.status} ${response.statusText}`);
        }
    }
    throw new Error("Unexpected error while polling for provisioning operation status");
}
//# sourceMappingURL=poll-provisioning-operations.js.map