const jwt = require('jsonwebtoken');
const { UnauthorizedError, ForbiddenError } = require('../utils/errors');
const logger = require('../utils/logger');

const authMiddleware = async (req, res, next) => {
  try {
    const authHeader = req.headers.authorization;
    if (!authHeader?.startsWith('Bearer ')) {
      throw new UnauthorizedError('No token provided');
    }

    const token = authHeader.split(' ')[1];
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    
    if (!decoded) {
      throw new UnauthorizedError('Invalid token');
    }

    if (decoded.exp < Date.now() / 1000) {
      throw new UnauthorizedError('Token expired');
    }

    req.user = decoded;
    next();
  } catch (error) {
    logger.error('Authentication error:', { error: error.message, path: req.path });
    next(new UnauthorizedError(error.message));
  }
};

const roleCheck = (roles = []) => {
  return (req, res, next) => {
    try {
      if (!req.user) {
        throw new UnauthorizedError('User not authenticated');
      }

      if (roles.length && !roles.includes(req.user.role)) {
        throw new ForbiddenError('Insufficient permissions');
      }

      next();
    } catch (error) {
      logger.error('Role check error:', { error: error.message, user: req.user?.id });
      next(error);
    }
  };
};

module.exports = { authMiddleware, roleCheck };