// JWT authentication middleware, extracted from app_api/routes/index.js
// into its own module for separation of concerns.
//
// Fixes from the code review of the original implementation:
//   1. jwt.verify was used with a callback but treated as synchronous:
//      next() ran unconditionally after it, so a request with an
//      invalid token both received res.sendStatus(401) AND continued
//      into the protected controller (double-response crash).
//   2. res.sendStatus(401).json(...) chained two response methods,
//      which throws "headers already sent".
//   3. The malformed-header check (headers.length < 1) could never be
//      true after String.split, so "Bearer" with no token fell through.
const jwt = require('jsonwebtoken');

function authenticateJWT(req, res, next) {
    const authHeader = req.headers['authorization'];
    if (!authHeader) {
        return res
            .status(401)
            .json({ message: 'Authorization header required' });
    }

    const parts = authHeader.split(' ');
    if (parts.length !== 2 || parts[0] !== 'Bearer' || !parts[1]) {
        return res
            .status(401)
            .json({ message: 'Malformed Authorization header' });
    }

    const token = parts[1];
    jwt.verify(token, process.env.JWT_SECRET, (err, verified) => {
        if (err) {
            return res
                .status(401)
                .json({ message: 'Token validation error' });
        }
        req.auth = verified; // Attach the decoded payload
        return next();       // Continue only after successful verification
    });
}

module.exports = authenticateJWT;
