"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.checkAuth = checkAuth;
const authManager_1 = require("../auth/authManager");
async function checkAuth(req, res, next) {
    // Check for Bearer token first for browser-based requests
    const authHeader = req.headers.authorization;
    if (authHeader && authHeader.startsWith('Bearer ')) {
        const token = authHeader.substring(7);
        const isValid = await authManager_1.authManager.verifyToken(token);
        if (isValid) {
            return next();
        }
        // If token is present but invalid, deny access immediately
        return res.status(401).json({ error: 'Unauthorized', message: 'Invalid or expired token provided.' });
    }
    // Fallback to file-based auth status for CLI
    const status = await authManager_1.authManager.getAuthStatus();
    if (status === 'authorized') {
        return next();
    }
    res.status(401).json({
        error: 'Unauthorized',
        message: `Your Repoburg license is ${status}. Please run 'repoburg login' to authorize this device.`,
    });
}
