import { select } from "@inquirer/prompts";
import { logger } from "../logger.js";
import { printCriticalFailureToConsoleAndExit, textOrJson } from "../output.js";
import settings from "../settings.js";
export async function fetchAccount(argv) {
    if (argv.account && typeof argv.account === "string") {
        return;
    }
    if (argv["api-key"]) {
        return;
    }
    const response = await fetch(`${settings.ZUPLO_DEVELOPER_API_ENDPOINT}/v1/accounts`, {
        method: "GET",
        headers: {
            Authorization: `Bearer ${argv.authToken}`,
        },
    });
    if (response.ok) {
        const accountsJson = await response.json();
        try {
            argv.account = await select({
                message: "Select the account",
                choices: accountsJson.data
                    .map((acc) => {
                    return {
                        name: acc.name,
                        value: acc.name,
                    };
                })
                    .sort((a, b) => a.name.localeCompare(b.name)),
            });
        }
        catch (error) {
            if (error.isTtyError || error.name === "ExitPromptError") {
                process.exit(0);
            }
            logger.trace("Failed to select account", error);
            process.exit(1);
        }
    }
    else {
        if (response.status === 404) {
            await printCriticalFailureToConsoleAndExit("You don't have a Zuplo account. Create one at https://zuplo.com and try again.");
        }
        logger.trace({
            status: response.status,
            statusText: response.statusText,
            response: textOrJson(await response.text()),
        }, "Failed to request accounts for user");
        await printCriticalFailureToConsoleAndExit("Error: Failed to request accounts for the user.");
    }
}
//# sourceMappingURL=get-account-param.js.map