import { logger } from "../../common/logger.js";
import { printCriticalFailureToConsoleAndExit, printResultToConsoleAndExitGracefully, printWarningToConsole, textOrJson, } from "../../common/output.js";
import { readLinkedConfig } from "../../common/read-linked-config.js";
import settings from "../../common/settings.js";
import { formatEnvironmentTypeLabel } from "../../common/utils/format-environment-type.js";
const PORTAL_BASE_URL = "https://portal.zuplo.com";
export async function info(argv) {
    const lines = [];
    const linked = await readLinkedConfig(argv);
    if (!linked.accountName || !linked.projectName) {
        lines.push("No project linked. Run `zuplo link` to connect a project.");
        await printResultToConsoleAndExitGracefully(lines.join("\n"));
        return;
    }
    const account = linked.accountName;
    const project = linked.projectName;
    let projectData;
    let fetchFailed = false;
    let response;
    try {
        const projectsUrl = new URL(`${settings.ZUPLO_DEVELOPER_API_ENDPOINT}/v1/projects`);
        projectsUrl.searchParams.set("accountName", account);
        response = await fetch(projectsUrl, {
            method: "GET",
            headers: {
                Authorization: `Bearer ${argv.authToken}`,
            },
        });
    }
    catch (error) {
        logger.debug(error, "Failed to fetch project details");
        fetchFailed = true;
    }
    if (response?.status === 401) {
        let body = "<unavailable>";
        try {
            body = await response.text();
        }
        catch (error) {
            logger.debug(error, "Failed to read response body");
        }
        logger.debug({
            status: response.status,
            statusText: response.statusText,
            response: textOrJson(body),
        }, "Failed to fetch project details");
        const message = argv["api-key"]
            ? "The provided --api-key was rejected. Check that it is valid and not expired, or run `zuplo login` to authenticate interactively."
            : "Your saved credentials were rejected. They may be expired — run `zuplo login` to re-authenticate, or pass a valid --api-key.";
        await printCriticalFailureToConsoleAndExit(message);
        return;
    }
    if (response?.ok) {
        try {
            const body = (await response.json());
            if (!Array.isArray(body.data)) {
                throw new Error("Projects API response did not include a data array");
            }
            logger.debug({ projects: body.data, linkedProject: project }, "Projects API response");
            projectData = body.data.find((p) => p.name === project);
        }
        catch (error) {
            logger.debug(error, "Failed to parse project details response");
            fetchFailed = true;
        }
    }
    else if (response) {
        let body = "<unavailable>";
        try {
            body = await response.text();
        }
        catch (error) {
            logger.debug(error, "Failed to read response body");
        }
        logger.debug({
            status: response.status,
            statusText: response.statusText,
            response: textOrJson(body),
        }, "Failed to fetch project details");
        if (response.status >= 400 && response.status < 500) {
            await printCriticalFailureToConsoleAndExit(`The Zuplo API returned ${response.status} ${response.statusText}. Verify the account "${account}" and your credentials.`);
            return;
        }
        fetchFailed = true;
    }
    lines.push(`Project: ${project}`);
    lines.push(`Account: ${account}`);
    lines.push(`Portal: ${PORTAL_BASE_URL}/${account}/${project}`);
    if (linked.environmentType) {
        const environmentTypeLabel = formatEnvironmentTypeLabel(linked.environmentType);
        if (environmentTypeLabel) {
            lines.push(`Environment Type: ${environmentTypeLabel}`);
        }
    }
    const projectNotFound = !fetchFailed && response?.ok === true && !projectData;
    if (!fetchFailed && !projectNotFound) {
        const sourceControlSettingsUrl = `${PORTAL_BASE_URL}/${account}/${project}/settings/source-control-settings`;
        if (projectData?.sourceRepoUrl) {
            lines.push(`Source Control: ${projectData.sourceRepoUrl}`);
        }
        else {
            lines.push(`Source Control: none, connect at ${sourceControlSettingsUrl}`);
        }
    }
    if (fetchFailed) {
        printWarningToConsole("Unable to fetch project details, some information may be missing");
    }
    else if (projectNotFound) {
        printWarningToConsole(`Project "${project}" was not found in account "${account}". Run \`zuplo link\` to link a project.`);
    }
    await printResultToConsoleAndExitGracefully(lines.join("\n"));
}
//# sourceMappingURL=handler.js.map