const { verifyAccessToken } = require('../utils/tokenUtils');

/**
 * Middleware to verify access token
 */
const verifyAccessTokenMiddleware = (req, res, next) => {
  try {
    // Get token from Authorization header
    const authHeader = req.headers['authorization'];
    
    if (!authHeader) {
      return res.status(401).json({
        status: false,
        message: 'Access token is required',
        data: null,
      });
    }

    // Extract token from "Bearer <token>"
    const token = authHeader.startsWith('Bearer ') 
      ? authHeader.slice(7) 
      : authHeader;

    // Verify token
    const decoded = verifyAccessToken(token);
    
    if (!decoded) {
      return res.status(401).json({
        status: false,
        message: 'Invalid or expired access token',
        data: null,
      });
    }

    // Attach user info to request
    req.admin = decoded;
    next();
  } catch (error) {
    return res.status(401).json({
      status: false,
      message: 'Token verification failed',
      data: null,
      error: error.message,
    });
  }
};

module.exports = verifyAccessTokenMiddleware;
