"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveAuth = resolveAuth;
exports.login = login;
exports.logout = logout;
exports.getServerUrl = getServerUrl;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const os = __importStar(require("os"));
const picocolors_1 = __importDefault(require("picocolors"));
const CONFIG_DIR = path.join(os.homedir(), '.config', 'longtail');
const CREDS_FILE = path.join(CONFIG_DIR, 'credentials.json');
/** Resolve auth from env → stored credentials → error */
async function resolveAuth() {
    // 1. Environment variables (CI / scripts)
    if (process.env.LT_TOKEN && process.env.LT_SERVER) {
        return { server: process.env.LT_SERVER, token: process.env.LT_TOKEN };
    }
    // 2. Stored credentials
    const creds = loadCredentials();
    if (!creds) {
        throw new Error('Not logged in. Run: ltc login');
    }
    // 3. Check expiry, auto-refresh if needed
    if (isExpired(creds.token)) {
        const fresh = await loginRequest(creds.server, creds.username, creds.password);
        saveCredentials({ ...creds, token: fresh.token, expiresAt: fresh.expiresAt });
        return { server: creds.server, token: fresh.token };
    }
    return { server: creds.server, token: creds.token };
}
/** Interactive or flag-based login */
async function login(options) {
    let { server, username, password } = options;
    // Interactive prompts for missing values
    if (!server) {
        server = await prompt('Server URL', 'http://localhost:3000');
    }
    if (!username) {
        username = await prompt('Username');
    }
    if (!password) {
        password = await prompt('Password');
    }
    server = server.replace(/\/+$/, '');
    const result = await loginRequest(server, username, password);
    saveCredentials({
        server,
        token: result.token,
        username: username,
        password: password,
        expiresAt: result.expiresAt,
    });
    console.log(`\n  ${picocolors_1.default.green('✓')} Logged in as ${picocolors_1.default.bold(result.displayName || username)} at ${picocolors_1.default.dim(server)}`);
    console.log(picocolors_1.default.dim(`    Token expires: ${result.expiresAt}\n`));
}
/** Clear stored credentials */
function logout() {
    if (fs.existsSync(CREDS_FILE)) {
        fs.unlinkSync(CREDS_FILE);
        console.log(`\n  ${picocolors_1.default.green('✓')} Logged out. Credentials cleared.\n`);
    }
    else {
        console.log(picocolors_1.default.dim('\n  No stored credentials found.\n'));
    }
}
/** Get the current server URL (for display purposes) */
function getServerUrl() {
    if (process.env.LT_SERVER)
        return process.env.LT_SERVER;
    const creds = loadCredentials();
    return creds?.server || null;
}
// ── Internal ─────────────────────────────────────────────────────────────
async function loginRequest(server, username, password) {
    const res = await fetch(`${server}/api/auth/login`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ username, password }),
    });
    if (!res.ok) {
        const body = await res.json().catch(() => ({}));
        throw new Error(body.error || `Login failed (HTTP ${res.status})`);
    }
    const data = await res.json();
    const token = data.token;
    // Decode JWT to get expiry
    const payload = JSON.parse(Buffer.from(token.split('.')[1], 'base64').toString());
    const expiresAt = new Date(payload.exp * 1000).toISOString();
    return {
        token,
        expiresAt,
        displayName: data.user?.display_name || data.user?.external_id,
    };
}
function loadCredentials() {
    try {
        if (!fs.existsSync(CREDS_FILE))
            return null;
        return JSON.parse(fs.readFileSync(CREDS_FILE, 'utf-8'));
    }
    catch {
        return null;
    }
}
function saveCredentials(creds) {
    fs.mkdirSync(CONFIG_DIR, { recursive: true });
    fs.writeFileSync(CREDS_FILE, JSON.stringify(creds, null, 2), { mode: 0o600 });
}
function isExpired(token) {
    try {
        const payload = JSON.parse(Buffer.from(token.split('.')[1], 'base64').toString());
        return Date.now() >= payload.exp * 1000 - 60_000; // 1min buffer
    }
    catch {
        return true;
    }
}
async function prompt(label, defaultValue) {
    const suffix = defaultValue ? picocolors_1.default.dim(` (${defaultValue})`) : '';
    process.stdout.write(`  ${label}${suffix}: `);
    return new Promise((resolve) => {
        let data = '';
        process.stdin.setEncoding('utf-8');
        process.stdin.once('data', (chunk) => {
            data = chunk.toString().trim();
            resolve(data || defaultValue || '');
        });
        process.stdin.resume();
    });
}
