import { select } from "@inquirer/prompts";
import { logger } from "../logger.js";
import { printCriticalFailureToConsoleAndExit, textOrJson } from "../output.js";
import settings from "../settings.js";
export async function fetchProject(argv) {
    if (argv.project && typeof argv.project === "string") {
        return;
    }
    if (!argv.account || typeof argv.account !== "string") {
        throw new Error("Invalid state: account is not set.");
    }
    const baseUrl = `${settings.ZUPLO_DEVELOPER_API_ENDPOINT}/v1/projects`;
    const queryParams = {
        accountName: argv.account,
    };
    const url = new URL(baseUrl);
    url.search = new URLSearchParams(queryParams).toString();
    const response = await fetch(url, {
        method: "GET",
        headers: {
            Authorization: `Bearer ${argv.authToken}`,
        },
    });
    if (response.ok) {
        const projectsJson = await response.json();
        try {
            argv.project = await select({
                message: "Select the project",
                choices: projectsJson.data
                    .map((project) => {
                    return {
                        name: project.name,
                        value: project.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 any projects configured for this account. Create a project in the Zuplo dashboard and try again.");
        }
        logger.trace({
            status: response.status,
            statusText: response.statusText,
            response: textOrJson(await response.text()),
        }, "Failed to request projects for account");
        await printCriticalFailureToConsoleAndExit("Error: Failed to request projects for the account.");
    }
}
//# sourceMappingURL=get-project-param.js.map