"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.normalizeTarget = normalizeTarget;
exports.loadCredentials = loadCredentials;
exports.saveCredentials = saveCredentials;
exports.clearCredentials = clearCredentials;
const common_utils_ts_1 = require("../utility/common_utils.js");
const node_fs_1 = __importDefault(require("node:fs"));
const node_path_1 = __importDefault(require("node:path"));
const ownerRWDenyAllOthers = 0o600;
/**
 * Normalizes a target operations API URL to a canonical form (with trailing slash).
 */
function normalizeTarget(target) {
    if (!target)
        return target;
    let normalized = target;
    if (!normalized.startsWith('http://') && !normalized.startsWith('https://')) {
        normalized = 'https://' + normalized;
    }
    try {
        const url = new URL(normalized);
        if (!url.port && !normalized.includes(':', normalized.indexOf('://') + 3)) {
            url.port = '9925';
        }
        normalized = url.toString();
    }
    catch {
        // If it's not a valid URL yet, we'll let it be handled later or it will fail
    }
    if (!normalized.endsWith('/')) {
        normalized += '/';
    }
    return normalized;
}
/**
 * Loads the JWT credentials from the ~/.harperdb/credentials.json file.
 */
function loadCredentials() {
    const credentialsFile = getCredentialsFile();
    try {
        return JSON.parse(node_fs_1.default.readFileSync(credentialsFile, 'utf8'));
    }
    catch (err) {
        if (err.code !== 'ENOENT') {
            throw new Error(`Error reading credentials file: ${err.message}`);
        }
    }
    return {
        last_target: null,
        targets: {},
    };
}
/**
 * Saves the JWT credentials to the ~/.harperdb/credentials.json file.
 */
function saveCredentials(target, tokens) {
    if (!target) {
        throw new Error('Target is required to save credentials.');
    }
    target = normalizeTarget(target);
    const allCredentials = loadCredentials();
    allCredentials.targets ||= {};
    allCredentials.targets[target] = tokens;
    allCredentials.last_target = target;
    try {
        node_fs_1.default.mkdirSync(getCredentialsDir(), { recursive: true });
        node_fs_1.default.writeFileSync(getCredentialsFile(), JSON.stringify(allCredentials, null, 2), { mode: ownerRWDenyAllOthers });
    }
    catch (err) {
        throw new Error(`Error saving credentials file: ${err.message}`);
    }
}
/**
 * Deletes the credentials for a specific target or all if no target provided.
 */
function clearCredentials(target) {
    const credentialsFile = getCredentialsFile();
    if (target) {
        target = normalizeTarget(target);
        const allCredentials = loadCredentials();
        if (allCredentials && allCredentials.targets) {
            if (allCredentials.targets[target]) {
                delete allCredentials.targets[target];
            }
            else {
                console.error(`No credentials found for ${target}`);
                process.exit(1);
            }
            if (allCredentials.last_target === target) {
                allCredentials.last_target = null;
            }
            try {
                node_fs_1.default.writeFileSync(credentialsFile, JSON.stringify(allCredentials, null, 2), {
                    mode: ownerRWDenyAllOthers,
                });
                console.log(`Logged out from ${target}`);
            }
            catch (err) {
                throw new Error(`Error clearing credentials file: ${err.message}`);
            }
        }
        else {
            console.error(`No credentials found for ${target}`);
            process.exit(1);
        }
    }
    else if (node_fs_1.default.existsSync(credentialsFile)) {
        try {
            node_fs_1.default.unlinkSync(credentialsFile);
            console.log('Logged out from all targets');
        }
        catch (err) {
            throw new Error(`Error clearing credentials file: ${err.message}`);
        }
    }
    else {
        console.log('No credentials found to clear.');
    }
}
function getCredentialsFile() {
    return node_path_1.default.join((0, common_utils_ts_1.getHomeDir)(), '.harperdb', 'credentials.json');
}
function getCredentialsDir() {
    return node_path_1.default.join((0, common_utils_ts_1.getHomeDir)(), '.harperdb');
}
//# sourceMappingURL=cliCredentials.js.map