const jwt = require('jsonwebtoken');

/**
 * Authentication middleware
 * Verifies JWT token and attaches user info to request
 */
function authenticateUser(req, res, next) {
  try {
    // In development mode, allow requests without auth for testing
    // SECURITY: This bypass only works if BOTH conditions are met:
    // 1. NODE_ENV is 'development'
    // 2. ALLOW_DEV_BYPASS is explicitly set to 'true'
    const isDevelopment = process.env.NODE_ENV === 'development';
    const allowDevBypass = process.env.ALLOW_DEV_BYPASS === 'true';

    if (isDevelopment && allowDevBypass) {
      // Check for token, but if not present, use demo user
      const authHeader = req.headers.authorization;

      if (!authHeader || !authHeader.startsWith('Bearer ')) {
        // Use demo user for development
        console.warn('⚠️  Development mode: Using demo user without authentication');
        req.user = {
          id: 'demo-user-123',
          email: 'demo@aethex.dev'
        };
        return next();
      }

      const token = authHeader.substring(7);

      // Try to verify, but don't fail if invalid
      try {
        const decoded = jwt.verify(token, process.env.JWT_SECRET);
        req.user = {
          id: decoded.userId,
          email: decoded.email
        };
      } catch {
        // Use demo user if token invalid
        console.warn('⚠️  Development mode: Invalid token, using demo user');
        req.user = {
          id: 'demo-user-123',
          email: 'demo@aethex.dev'
        };
      }

      return next();
    }

    // Production: Strict auth required
    const authHeader = req.headers.authorization;
    
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return res.status(401).json({ 
        success: false, 
        error: 'Authentication required. Please provide a valid token.' 
      });
    }
    
    const token = authHeader.substring(7); // Remove 'Bearer ' prefix
    
    // Verify token
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    
    // Attach user info to request
    req.user = {
      id: decoded.userId,
      email: decoded.email
    };
    
    next();
  } catch (error) {
    if (error.name === 'JsonWebTokenError') {
      return res.status(401).json({ 
        success: false, 
        error: 'Invalid authentication token' 
      });
    }
    
    if (error.name === 'TokenExpiredError') {
      return res.status(401).json({ 
        success: false, 
        error: 'Authentication token has expired' 
      });
    }
    
    return res.status(500).json({ 
      success: false, 
      error: 'Authentication failed' 
    });
  }
}

/**
 * Validate domain format
 * @param {string} domain - Domain to validate
 * @returns {boolean} Whether domain is valid
 */
function isValidDomain(domain) {
  if (!domain || typeof domain !== 'string') {
    return false;
  }
  
  // Basic domain validation regex
  // Allows: example.com, sub.example.com, example.aethex
  const domainRegex = /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9]$/i;
  
  return domainRegex.test(domain) && domain.length <= 253;
}

module.exports = {
  authenticateUser,
  isValidDomain
};
