import { select } from "@inquirer/prompts";
import { logger } from "../logger.js";
import { printCriticalFailureToConsoleAndExit, textOrJson } from "../output.js";
import { confirmLinkedValue, readLinkedConfig, USE_LINKED_DETAILS, } from "../read-linked-config.js";
import settings from "../settings.js";
import { isInteractiveTerminal } from "../terminal.js";
export async function fetchAccount(argv) {
    if (argv.account && typeof argv.account === "string") {
        return;
    }
    if (argv["api-key"]) {
        return;
    }
    if (argv[USE_LINKED_DETAILS] !== false) {
        const linked = await readLinkedConfig(argv);
        if (linked.accountName) {
            if (!isInteractiveTerminal()) {
                argv.account = linked.accountName;
                return;
            }
            const useLinked = await confirmLinkedValue(`Use linked account '${linked.accountName}'?`);
            if (useLinked) {
                argv.account = linked.accountName;
                return;
            }
            argv[USE_LINKED_DETAILS] = false;
        }
    }
    if (!isInteractiveTerminal()) {
        await printCriticalFailureToConsoleAndExit("Error: --account is required in non-interactive environments (e.g. CI/CD).\nUse the --account flag to specify an account name.");
        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(1);
            }
            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