import { select, input } from "@inquirer/prompts";
import { logger } from "../logger.js";
import { printCriticalFailureToConsoleAndExit, textOrJson } from "../output.js";
import settings from "../settings.js";
import { readFile } from "node:fs/promises";
import { createProject } from "../../project/create/handler.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();
        if (projectsJson.data.length === 0) {
            let projectName;
            try {
                const packageJson = JSON.parse(await readFile("package.json", "utf-8"));
                projectName = packageJson.name;
            }
            catch (error) {
                logger.trace("Failed to read package.json", error);
            }
            const outputProjectName = await input({
                message: "You don't have any projects configured for this account. Please enter a project name to create one.",
                default: projectName,
            });
            await createProject({
                name: outputProjectName,
                account: argv.account,
                authToken: argv.authToken,
            });
            argv.project = outputProjectName;
            logger.trace(`Project ${outputProjectName} created successfully.`);
        }
        else {
            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 project", 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