/**
 * Admin Authentication Middleware
 * Ensures user is authenticated and has admin role
 */

const jwt = require('jsonwebtoken');

/**
 * Authenticate JWT token from Authorization header
 */
const authenticateToken = (req, res, next) => {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];

  if (!token) {
    return res.status(401).json({
      success: false,
      error: 'Access token required',
      message: 'No authorization token provided'
    });
  }

  jwt.verify(token, process.env.JWT_SECRET, (err, user) => {
    if (err) {
      console.error('[Auth] Token verification failed:', err.message);
      return res.status(403).json({
        success: false,
        error: 'Invalid or expired token',
        message: err.message
      });
    }

    req.user = user;
    next();
  });
};

/**
 * Check if user has admin role
 */
const authenticateAdmin = (req, res, next) => {
  if (!req.user) {
    return res.status(401).json({
      success: false,
      error: 'Not authenticated',
      message: 'User authentication required'
    });
  }

  if (req.user.role !== 'admin') {
    console.warn(`[Auth] Non-admin user ${req.user.userId} attempted admin access: ${req.method} ${req.path}`);
    return res.status(403).json({
      success: false,
      error: 'Admin access required',
      message: 'Only administrators can access this endpoint'
    });
  }

  next();
};

/**
 * Optional: Check super admin role (for sensitive operations)
 */
const authenticateSuperAdmin = (req, res, next) => {
  if (!req.user) {
    return res.status(401).json({
      success: false,
      error: 'Not authenticated',
      message: 'User authentication required'
    });
  }

  if (req.user.role !== 'superadmin' && req.user.role !== 'admin') {
    return res.status(403).json({
      success: false,
      error: 'Super admin access required',
      message: 'Only super administrators can access this endpoint'
    });
  }

  next();
};

/**
 * Middleware chain: Authenticate token AND check admin role
 */
const requireAdmin = [authenticateToken, authenticateAdmin];
const requireSuperAdmin = [authenticateToken, authenticateSuperAdmin];

module.exports = {
  authenticateToken,
  authenticateAdmin,
  authenticateSuperAdmin,
  requireAdmin,
  requireSuperAdmin
};
