// ─────────────────────────────────────────────────────────────────────────────
// Nexus Prime Licensing — Web Auth (CLI Login)
//
// Handles email+password login from CLI to nexus-prime.cfd.
// Stores auth tokens at ~/.nexus-prime/auth.json for license sync.
// ─────────────────────────────────────────────────────────────────────────────
import fs from 'fs';
import path from 'path';
import os from 'os';
const AUTH_FILE = path.join(os.homedir(), '.nexus-prime', 'auth.json');
const API_BASE = process.env.NEXUS_WEB_API_URL ?? 'https://nexus-prime.cfd';
/**
 * Login to nexus-prime.cfd and store auth tokens locally. Errors are
 * normalised so signup/signin failures don't surface raw HTTP codes —
 * users get something actionable, plus a reminder that the local no-license
 * grace period is intentionally short and licenses are reviewed manually.
 */
export async function loginFromCLI(email, password) {
    let res;
    try {
        res = await fetch(`${API_BASE}/api/auth/login`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ email, password }),
            signal: AbortSignal.timeout(15_000),
        });
    }
    catch (err) {
        const reason = err instanceof Error ? err.message : String(err);
        throw new Error(`Could not reach ${API_BASE}: ${reason}. `
            + `If your 3-day no-license grace is over, request a license at ${API_BASE}/account `
            + `or email adarsh@nexus-prime.cfd. Licenses are shared within 24 hours.`);
    }
    if (!res.ok) {
        const body = await res.json().catch(() => ({}));
        const detail = body.error;
        if (res.status === 401 || res.status === 403) {
            throw new Error(detail
                ? `Sign-in rejected: ${detail}`
                : `Sign-in rejected: bad email or password. Reset at ${API_BASE}/account/reset.`);
        }
        if (res.status === 404) {
            throw new Error(`No account for ${email}. Sign up at ${API_BASE}/signup, then retry. `
                + `If you need manual help, email adarsh@nexus-prime.cfd. Licenses are shared within 24 hours.`);
        }
        if (res.status >= 500) {
            throw new Error(`Server error (${res.status}) at ${API_BASE}. Try again shortly, or email adarsh@nexus-prime.cfd for a manual license review within 24 hours.`);
        }
        throw new Error(detail ?? `Login failed (HTTP ${res.status})`);
    }
    const data = await res.json();
    if (!data.session?.access_token) {
        throw new Error(`Sign-in succeeded but ${API_BASE} returned no access token. Contact support.`);
    }
    writeAuthToken(data.session.access_token, data.session.refresh_token, email);
    return { email, plan: data.plan };
}
/**
 * Read stored auth token. Returns null if not logged in.
 */
export function readAuthToken() {
    try {
        if (!fs.existsSync(AUTH_FILE))
            return null;
        const raw = fs.readFileSync(AUTH_FILE, 'utf8');
        const tokens = JSON.parse(raw);
        return tokens.access_token || null;
    }
    catch {
        return null;
    }
}
/**
 * Read stored auth info (email + tokens).
 */
export function readAuthInfo() {
    try {
        if (!fs.existsSync(AUTH_FILE))
            return null;
        const raw = fs.readFileSync(AUTH_FILE, 'utf8');
        return JSON.parse(raw);
    }
    catch {
        return null;
    }
}
/**
 * Check if user is logged in.
 */
export function isLoggedIn() {
    return readAuthToken() !== null;
}
/**
 * Clear stored auth tokens (logout).
 */
export function logout() {
    try {
        if (fs.existsSync(AUTH_FILE)) {
            fs.unlinkSync(AUTH_FILE);
        }
    }
    catch {
        // Best-effort
    }
}
/**
 * Store auth tokens to disk.
 */
function writeAuthToken(accessToken, refreshToken, email) {
    const dir = path.dirname(AUTH_FILE);
    fs.mkdirSync(dir, { recursive: true });
    const tokens = {
        access_token: accessToken,
        refresh_token: refreshToken,
        email,
        updated_at: new Date().toISOString(),
    };
    fs.writeFileSync(AUTH_FILE, JSON.stringify(tokens, null, 2), { encoding: 'utf8', mode: 0o600 });
}
