"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = require("express");
const routing_strategy_1 = require("../../cliproxy/routing/routing-strategy");
const auth_middleware_1 = require("../middleware/auth-middleware");
const router = (0, express_1.Router)();
router.use((req, res, next) => {
    if ((0, auth_middleware_1.requireLocalAccessWhenAuthDisabled)(req, res, 'CLIProxy routing endpoints require localhost access when dashboard auth is disabled.')) {
        next();
    }
});
router.get('/routing/strategy', async (_req, res) => {
    try {
        res.json(await (0, routing_strategy_1.readCliproxyRoutingState)());
    }
    catch (error) {
        res.status(502).json({ error: error.message });
    }
});
router.put('/routing/strategy', async (req, res) => {
    const strategy = (0, routing_strategy_1.normalizeCliproxyRoutingStrategy)(req.body?.value ?? req.body?.strategy);
    if (!strategy) {
        res.status(400).json({ error: 'Invalid strategy. Use: round-robin or fill-first' });
        return;
    }
    try {
        res.json(await (0, routing_strategy_1.applyCliproxyRoutingStrategy)(strategy));
    }
    catch (error) {
        res.status(502).json({ error: error.message });
    }
});
router.get('/routing/session-affinity', async (_req, res) => {
    try {
        res.json(await (0, routing_strategy_1.readCliproxySessionAffinityState)());
    }
    catch (error) {
        res.status(502).json({ error: error.message });
    }
});
router.put('/routing/session-affinity', async (req, res) => {
    const enabled = (0, routing_strategy_1.normalizeCliproxySessionAffinityEnabled)(req.body?.enabled ?? req.body?.value);
    const ttl = req.body?.ttl;
    const normalizedTtl = ttl === undefined ? undefined : ((0, routing_strategy_1.normalizeCliproxySessionAffinityTtl)(ttl) ?? undefined);
    if (enabled === null || (ttl !== undefined && !normalizedTtl)) {
        res.status(400).json({
            error: 'Invalid session affinity payload. Use enabled=true|false and ttl like 30m or 1h.',
        });
        return;
    }
    try {
        const result = await (0, routing_strategy_1.applyCliproxySessionAffinitySettings)({
            enabled,
            ttl: normalizedTtl,
        });
        if (!result.manageable || result.applied === 'unsupported') {
            res.status(400).json({
                error: result.message || 'Session affinity is not supported for this target.',
            });
            return;
        }
        res.json(result);
    }
    catch (error) {
        res.status(502).json({ error: error.message });
    }
});
exports.default = router;
//# sourceMappingURL=cliproxy-routing-routes.js.map