// ─────────────────────────────────────────────────────────────────────────────
// Nexus Prime Licensing — License Sync
//
// Fetches the user's latest signed license key from nexus-prime.cfd.
// Requires prior login via `nexus-prime license login` (stores auth token).
// ─────────────────────────────────────────────────────────────────────────────
import { readAuthToken } from './web-auth.js';
import { getSharedLicenseManager } from './license-manager.js';
const API_BASE = process.env.NEXUS_WEB_API_URL ?? 'https://nexus-prime.cfd';
/**
 * Fetch the user's latest license key from the website API and activate it.
 * @throws If not logged in or if the API request fails.
 *
 * Set NEXUS_LICENSE_SYNC_OFFLINE=1 to skip the network round-trip and return
 * the current cached status instead (useful in tests and air-gapped envs).
 */
export async function syncLicense() {
    const offlineFlag = process.env.NEXUS_LICENSE_SYNC_OFFLINE;
    if (offlineFlag && offlineFlag !== '0' && offlineFlag.toLowerCase() !== 'false') {
        return getSharedLicenseManager().getStatus();
    }
    const authToken = readAuthToken();
    if (!authToken) {
        throw new Error('Not logged in. Run: nexus-prime license login\n' +
            'Or request a license: https://nexus-prime.cfd/account\n' +
            'Email fallback: adarsh@nexus-prime.cfd');
    }
    const res = await fetch(`${API_BASE}/api/license/current`, {
        headers: { Authorization: `Bearer ${authToken}` },
        signal: AbortSignal.timeout(10_000),
    });
    if (!res.ok) {
        if (res.status === 401) {
            throw new Error('Session expired. Please login again: nexus-prime license login');
        }
        const body = await res.json().catch(() => ({}));
        throw new Error(body.error ?? `License sync failed (HTTP ${res.status})`);
    }
    const data = await res.json();
    if (!data.signed_key) {
        throw new Error('No license key found. Request one at https://nexus-prime.cfd/account or email adarsh@nexus-prime.cfd. Licenses are reviewed within 24 hours.');
    }
    const lm = getSharedLicenseManager();
    return lm.activate(data.signed_key);
}
/**
 * Request a plan upgrade through the website API.
 * @throws If not logged in or if the API request fails.
 */
export async function requestUpgrade(requestedPlan) {
    const authToken = readAuthToken();
    if (!authToken) {
        throw new Error('Not logged in. Run: nexus-prime license login, or use https://nexus-prime.cfd/account / adarsh@nexus-prime.cfd.');
    }
    const res = await fetch(`${API_BASE}/api/license/request-upgrade`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${authToken}`,
        },
        body: JSON.stringify({ requested_plan: requestedPlan }),
        signal: AbortSignal.timeout(10_000),
    });
    if (!res.ok) {
        const body = await res.json().catch(() => ({}));
        throw new Error(body.error ?? `Upgrade request failed (HTTP ${res.status})`);
    }
    const data = await res.json();
    return { requestId: data.request_id, status: data.status };
}
