// ─────────────────────────────────────────────────────────────────────────────
// Nexus Prime Dashboard — License & Usage Routes
//
// GET  /api/license/pcu        — full PCU snapshot (JSON)
// GET  /api/license/status     — license status + formatted bars
// POST /api/license/activate   — activate a license key { key: "..." }
// POST /api/license/deactivate — deactivate current license
// POST /api/license/sync       — sync license from nexus-prime.cfd
// ─────────────────────────────────────────────────────────────────────────────
import { getSharedLicenseManager, snapshotPCU, formatPCUStatus, } from '../../licensing/index.js';
export const handleLicenseRoutes = async (ctx, req, res, url) => {
    // ── PCU snapshot (raw JSON) ──────────────────────────────────────────────
    if (req.method === 'GET' && url.pathname === '/api/license/pcu') {
        const pcu = snapshotPCU();
        ctx.respondJson(res, pcu);
        return true;
    }
    // ── License status with formatted bars ───────────────────────────────────
    if (req.method === 'GET' && url.pathname === '/api/license/status') {
        const lm = getSharedLicenseManager();
        const status = lm.getStatus();
        const pcu = snapshotPCU();
        const formatted = formatPCUStatus(pcu);
        ctx.respondJson(res, {
            status,
            pcu,
            formatted,
        });
        return true;
    }
    // ── Activate license key ─────────────────────────────────────────────────
    if (req.method === 'POST' && url.pathname === '/api/license/activate') {
        const body = await ctx.readJsonBody(req);
        const key = body?.key;
        if (typeof key !== 'string' || !key.trim()) {
            ctx.respondJson(res, { error: 'Missing "key" in request body' }, 400);
            return true;
        }
        const lm = getSharedLicenseManager();
        const result = lm.activate(key.trim());
        ctx.respondJson(res, {
            success: result.valid,
            status: result,
            message: result.valid
                ? `License activated: ${result.tier.toUpperCase()} plan`
                : `Activation failed: ${result.degradedReason ?? 'invalid key'}`,
        });
        return true;
    }
    // ── Deactivate license ───────────────────────────────────────────────────
    if (req.method === 'POST' && url.pathname === '/api/license/deactivate') {
        const lm = getSharedLicenseManager();
        lm.deactivate();
        ctx.respondJson(res, {
            success: true,
            message: 'License deactivated. Running on free tier.',
            status: lm.getStatus(),
        });
        return true;
    }
    // ── Sync license from website API ────────────────────────────────────────
    if (req.method === 'POST' && url.pathname === '/api/license/sync') {
        try {
            const { syncLicense } = await import('../../licensing/license-sync.js');
            const result = await syncLicense();
            ctx.respondJson(res, {
                success: result.valid,
                status: result,
                message: result.valid
                    ? `License synced: ${result.tier.toUpperCase()} plan`
                    : `Sync failed: ${result.degradedReason ?? 'unknown'}`,
            });
        }
        catch (err) {
            ctx.respondJson(res, {
                success: false,
                error: err instanceof Error ? err.message : String(err),
                message: 'License sync failed. Make sure you are logged in: nexus-prime license login',
            }, 500);
        }
        return true;
    }
    return false;
};
