const jwt = require('jsonwebtoken');
const config = require('../config/env');

const authenticateToken = (req, res, next) => {
  // Try to get token from cookie first (new secure method)
  let token = req.cookies?.token;
  
  // Fallback: Check Authorization header for backward compatibility
  if (!token) {
    const authHeader = req.headers['authorization'];
    token = authHeader && authHeader.split(' ')[1]; // Bearer TOKEN
  }

  if (!token) {
    return res.status(401).json({ 
      success: false, 
      message: 'Zugriff verweigert. Kein Token bereitgestellt.' 
    });
  }

  try {
    const decoded = jwt.verify(token, config.jwtSecret);
    req.user = decoded;
    next();
  } catch (error) {
    return res.status(403).json({ 
      success: false, 
      message: 'Ungültiger oder abgelaufener Token.' 
    });
  }
};

module.exports = { authenticateToken };
