const jwt = require('jsonwebtoken');
const { User } = require('../models');

const authenticateToken = async (req, res, next) => {
  try {
    const debug = process.env.NODE_ENV !== 'production';
    if (debug) {
      console.log('🔐 [Auth] Authenticating request:', req.method, req.path);
    }
    const authHeader = req.headers['authorization'];
    if (debug) {
      console.log('🔐 [Auth] Authorization header present:', !!authHeader);
    }
    
    const token = authHeader?.split(' ')[1]; // Bearer TOKEN

    if (!token) {
      if (debug) {
        console.log('❌ [Auth] No token provided');
      }
      return res.status(401).json({ 
        success: false, 
        message: 'Access token required' 
      });
    }

    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    if (debug) {
      console.log('✅ [Auth] Token verified successfully');
      console.log('🔐 [Auth] User ID from token:', decoded.userId);
      console.log('🔐 [Auth] User role from token:', decoded.role);
    }
    
    // Get user from database
    const user = await User.findByPk(decoded.userId);
    
    if (!user) {
      if (debug) {
        console.log('❌ [Auth] User NOT found in database:', decoded.userId);
      }
      return res.status(401).json({ 
        success: false, 
        message: 'Invalid or inactive user' 
      });
    }
    
    if (debug) {
      console.log('✅ [Auth] User found:', user.full_name);
      console.log('🔐 [Auth] User is_active:', user.is_active);
      console.log('🔐 [Auth] User role:', user.role);
    }
    
    if (!user.is_active) {
      if (debug) {
        console.log('❌ [Auth] User is inactive');
      }
      return res.status(401).json({ 
        success: false, 
        message: 'Invalid or inactive user' 
      });
    }

    if (debug) {
      console.log('✅ [Auth] Authentication successful');
    }
    req.user = user;
    next();
  } catch (error) {
    const debug = process.env.NODE_ENV !== 'production';
    if (debug) {
      console.log('❌ [Auth] Error during authentication:', error.name);
      console.log('❌ [Auth] Error message:', error.message);
    }
    
    if (error.name === 'JsonWebTokenError') {
      if (debug) {
        console.log('❌ [Auth] JWT verification failed');
      }
      return res.status(401).json({ 
        success: false, 
        message: 'Invalid token' 
      });
    }
    if (error.name === 'TokenExpiredError') {
      if (debug) {
        console.log('❌ [Auth] Token has expired');
      }
      return res.status(401).json({ 
        success: false, 
        message: 'Token expired' 
      });
    }
    
    console.error('❌ [Auth] Unexpected error:', error);
    return res.status(500).json({ 
      success: false, 
      message: 'Internal server error' 
    });
  }
};

const requireRole = (roles) => {
  return (req, res, next) => {
    if (!req.user) {
      return res.status(401).json({ 
        success: false, 
        message: 'Authentication required' 
      });
    }

    if (!roles.includes(req.user.role)) {
      return res.status(403).json({ 
        success: false, 
        message: 'Insufficient permissions' 
      });
    }

    next();
  };
};

const requireManager = requireRole(['manager']);
const requireMember = requireRole(['member']);
const requireAnyRole = requireRole(['manager', 'member']);

module.exports = {
  authenticateToken,
  requireRole,
  requireManager,
  requireMember,
  requireAnyRole
};
