import { confirm } from "@inquirer/prompts";
import { login } from "../../login/login.js";
import { getAuthToken } from "../../login/tokens.js";
import { printCriticalFailureToConsoleAndExit } from "../output.js";
import { isInteractiveTerminal } from "../terminal.js";
async function fail() {
    await printCriticalFailureToConsoleAndExit(`You are not authenticated. Please run \`zuplo login\` to log in or set an api key.`);
}
async function failNonInteractive() {
    await printCriticalFailureToConsoleAndExit(`Authentication required. This command requires an API key when running in non-interactive mode (e.g., CI/CD).

Please provide an API key using one of the following methods:
  1. Pass the --api-key (or --apikey) flag: zuplo <command> --api-key YOUR_API_KEY
  2. Set the environment variable: ZUPLO_API_KEY=YOUR_API_KEY

You can create an API key at: https://portal.zuplo.com`);
}
function makeAuthenticate(opts) {
    return async function authenticate(argv) {
        if (argv["api-key"]) {
            Object.assign(argv, { authToken: argv["api-key"] });
            return;
        }
        let token = await getAuthToken();
        if (!token) {
            if (!isInteractiveTerminal()) {
                return failNonInteractive();
            }
            if (!opts.promptToLogin) {
                return fail();
            }
            const result = await confirm({
                message: "You are not authenticated. Would you like to log in?",
            });
            if (!result) {
                return fail();
            }
            await login();
            token = await getAuthToken();
            if (!token) {
                return fail();
            }
        }
        Object.assign(argv, { authToken: token });
    };
}
export const authenticate = makeAuthenticate({ promptToLogin: true });
export const authenticateNoPrompt = makeAuthenticate({ promptToLogin: false });
//# sourceMappingURL=authentication.js.map