const JWTService = require('../utils/jwt');
const { ErrorHandler } = require('../helpers/error');

function setUser(req, decoded) {
  req.user = {
    userId: decoded.user_id,
    fullname: decoded.user_fullname,
    username: decoded.user_name,
    email: decoded.user_email,
    roleId: decoded.role_id,
    roleName: decoded.role_name,
    is_sa: decoded.is_sa
  };
}

function verifyAccessToken(req, res, next) {
  try {
    let token = req.cookies?.accessToken;

    if (!token) {
      const authHeader = req.headers.authorization;
      if (authHeader && authHeader.startsWith('Bearer')) {
        token = authHeader.split(' ')[1];
      } else {
        token = req.query.token;
      }
    }

    if (!token) {
      throw new ErrorHandler(401, 'Access Token is required');
    }

    const decoded = JWTService.verifyToken(token);

    req.user = decoded;

    next();
  } catch (error) {
    if (error.name === 'TokenExpiredError') {
      return next(new ErrorHandler(401, 'Access token expired'));
    }

    if (error.name === 'JsonWebTokenError') {
      return next(new ErrorHandler(401, 'Invalid access token'));
    }

    return next(new ErrorHandler(500, 'Internal authentication error'));
  }
}

module.exports = {
  verifyAccessToken
};