"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createAuthMiddleware = createAuthMiddleware;
const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
function createAuthMiddleware(config) {
    const expectedToken = config.signalsAdminToken;
    const jwtSecret = config.jwtSecret;
    return (req, res, next) => {
        const authHeader = req.headers.authorization ?? "";
        const token = authHeader.startsWith("Bearer ") ? authHeader.slice(7) : undefined;
        if (!token) {
            res.status(401).json({ error: "Unauthorized." });
            return;
        }
        // First try to verify as a JWT issued by the main admin server.
        if (jwtSecret) {
            try {
                const decoded = jsonwebtoken_1.default.verify(token, jwtSecret);
                if (decoded.role === "admin" || decoded.role === "super_admin") {
                    req.adminUser = { id: decoded.id ?? "admin", role: decoded.role };
                    next();
                    return;
                }
            }
            catch {
                // Not a valid JWT for this secret — fall through to static-token check.
            }
        }
        // Fall back to static shared-secret auth.
        if (!expectedToken) {
            res.status(500).json({ error: "Admin API is not configured with an authentication token." });
            return;
        }
        if (token !== expectedToken) {
            res.status(401).json({ error: "Unauthorized." });
            return;
        }
        req.adminToken = token;
        next();
    };
}
