"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.login = login;
const chalk_1 = __importDefault(require("chalk"));
const dotenv_1 = __importDefault(require("dotenv"));
const node_fs_1 = __importDefault(require("node:fs"));
const node_path_1 = __importDefault(require("node:path"));
const inquirer_1 = __importDefault(require("inquirer"));
const cliCredentials_ts_1 = require("./cliCredentials.js");
const cliOperations_ts_1 = require("./cliOperations.js");
/**
 * Executes the login command.
 */
async function login(targetArg, usernameArg) {
    dotenv_1.default.config();
    console.log(chalk_1.default.cyan('\nHarper login'));
    console.log(chalk_1.default.gray('Harper apps can be deployed to Fabric for free, where one runtime can house your app, database, cache, and messaging.'));
    console.log(chalk_1.default.gray('https://fabric.harper.fast/\n'));
    console.log(chalk_1.default.gray('If you create a cluster, you can enter your credentials here. They will be exchanged for a JWT from'));
    console.log(chalk_1.default.gray('your cluster, which will be saved inside ~/.harperdb/credentials.json\n'));
    const defaultTarget = process.env.HARPER_CLI_TARGET || process.env.CLI_TARGET;
    let target = targetArg || defaultTarget;
    if (!targetArg) {
        const { target: input } = await inquirer_1.default.prompt({
            type: 'input',
            name: 'target',
            message: 'Cluster Target URL:',
            default: defaultTarget,
        });
        if (input?.trim()) {
            target = input.trim();
        }
    }
    if (!target) {
        console.error(chalk_1.default.red('Target URL is required.'));
        process.exit(1);
    }
    target = (0, cliCredentials_ts_1.normalizeTarget)(target);
    let targetUsername = usernameArg;
    if (!targetUsername) {
        if (process.env.CLI_TARGET_USERNAME) {
            targetUsername = process.env.CLI_TARGET_USERNAME;
            console.log(chalk_1.default.gray(`Using username from CLI_TARGET_USERNAME environment variable: ${targetUsername}`));
        }
        else if (process.env.HARPER_CLI_USERNAME) {
            targetUsername = process.env.HARPER_CLI_USERNAME;
            console.log(chalk_1.default.gray(`Using username from HARPER_CLI_USERNAME environment variable: ${targetUsername}`));
        }
        else {
            ({ username: targetUsername } = await inquirer_1.default.prompt({
                type: 'input',
                name: 'username',
                message: 'Cluster Username:',
            }));
        }
    }
    let targetPassword = process.env.CLI_TARGET_PASSWORD || process.env.HARPER_CLI_PASSWORD;
    if (targetPassword) {
        const envVarName = process.env.CLI_TARGET_PASSWORD ? 'CLI_TARGET_PASSWORD' : 'HARPER_CLI_PASSWORD';
        console.log(chalk_1.default.gray(`Using password from ${envVarName} environment variable.`));
    }
    else {
        // `type: 'password'` with no `mask` hides input entirely — nothing is echoed until Enter.
        ({ password: targetPassword } = await inquirer_1.default.prompt({
            type: 'password',
            name: 'password',
            message: 'Cluster Password:',
        }));
    }
    if (!targetUsername || !targetPassword) {
        console.error('Username and password are required.');
        process.exit(1);
    }
    const req = {
        operation: 'create_authentication_tokens',
        username: targetUsername,
        password: targetPassword,
        target,
    };
    const response = await (0, cliOperations_ts_1.cliOperations)(req, true);
    if (response && response.operation_token) {
        const resolvedTarget = response.target || req.target || response.resolvedTarget || target;
        try {
            (0, cliCredentials_ts_1.saveCredentials)(resolvedTarget, {
                operation_token: response.operation_token,
                refresh_token: response.refresh_token,
            });
        }
        catch (err) {
            console.error(chalk_1.default.red(err instanceof Error ? err.message : String(err)));
            process.exit(1);
        }
        // If CLI_TARGET is not in process.env before we started (meaning it's not in .env or other env vars),
        // and we just logged in with a target, let's consider adding it to .env. This is non-critical
        // (credentials are already saved), so a filesystem error here must not crash the CLI.
        try {
            const envPath = node_path_1.default.join(process.cwd(), '.env');
            if (node_fs_1.default.existsSync(envPath)) {
                const envConfig = dotenv_1.default.parse(node_fs_1.default.readFileSync(envPath));
                if (!envConfig.CLI_TARGET &&
                    !envConfig.HARPER_CLI_TARGET &&
                    !process.env.CLI_TARGET &&
                    !process.env.HARPER_CLI_TARGET) {
                    const envLine = `\nHARPER_CLI_TARGET=${resolvedTarget}\n`;
                    node_fs_1.default.appendFileSync(envPath, envLine);
                    console.log(`Added HARPER_CLI_TARGET to .env`);
                }
            }
        }
        catch (err) {
            console.error(chalk_1.default.yellow(`Could not update .env: ${err instanceof Error ? err.message : String(err)}`));
        }
        console.log(`Successfully logged in to ${resolvedTarget} and saved credentials.`);
        process.exit(0);
    }
    else {
        throw new Error('Failed to retrieve authentication tokens.');
    }
}
//# sourceMappingURL=login.js.map