/**
 * Bearer Token Authentication Middleware
 * Validates API key from Authorization header
 */

const authMiddleware = (req, res, next) => {
  const authHeader = req.headers.authorization;
  
  if (!authHeader) {
    return res.status(401).json({ error: 'Authorization header missing' });
  }

  const parts = authHeader.split(' ');
  if (parts.length !== 2 || parts[0] !== 'Bearer') {
    return res.status(401).json({ error: 'Invalid authorization format. Use: Bearer <token>' });
  }

  const token = parts[1];
  const apiKey = process.env.API_KEY;

  if (!apiKey) {
    console.error('[Auth] API_KEY not configured in environment variables');
    return res.status(500).json({ error: 'Server configuration error' });
  }

  if (token !== apiKey) {
    return res.status(403).json({ error: 'Invalid API key' });
  }

  req.apiKey = token;
  next();
};

module.exports = { authMiddleware };

