import jwt from 'jsonwebtoken';
import { User } from '../models/User.js';

export const authenticateToken = async (req, res, next) => {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];

  if (!token) {
    return res.status(401).json({ error: 'Access token required' });
  }

  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    const user = await User.findById(decoded.userId);
    
    if (!user) {
      return res.status(401).json({ error: 'Invalid token' });
    }

    req.user = user;
    next();
  } catch (error) {
    return res.status(403).json({ error: 'Invalid or expired token' });
  }
};

export const authenticateApiKey = async (req, res, next) => {
  const apiKey = req.headers['x-api-key'] || req.query.api_key;

  if (!apiKey) {
    return res.status(401).json({ error: 'API key required' });
  }

  try {
    const user = await User.findByApiKey(apiKey);
    
    if (!user) {
      return res.status(401).json({ error: 'Invalid API key' });
    }

    req.user = user;
    next();
  } catch (error) {
    return res.status(500).json({ error: 'Authentication error' });
  }
};

export const checkUsageLimits = async (req, res, next) => {
  try {
    const userId = req.user.id;
    const stats = await User.getUsageStats(userId);
    
    if (!stats) {
      return res.status(404).json({ error: 'User stats not found' });
    }

    // Check monthly limits
    if (stats.images_processed_this_month >= stats.monthly_image_limit) {
      return res.status(429).json({ 
        error: 'Monthly image processing limit exceeded',
        currentUsage: stats.images_processed_this_month,
        limit: stats.monthly_image_limit
      });
    }

    // Check for too many active jobs
    if (stats.active_jobs > 10) {
      return res.status(429).json({ 
        error: 'Too many active processing jobs. Please wait for current jobs to complete.'
      });
    }

    req.userStats = stats;
    next();
  } catch (error) {
    return res.status(500).json({ error: 'Usage limit check failed' });
  }
};

export const generateToken = (userId) => {
  return jwt.sign({ userId }, process.env.JWT_SECRET, { expiresIn: '7d' });
};