const jwt = require('jsonwebtoken');
const path = require('path');
const {models} = require(path.resolve(process.env.ROOT_PATH, './db/db.js'));

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

  if (!token) {
    return res.status(401).json({ error: 'Authentication required' });
  }
  
  jwt.verify(token, process.env.JWT_SECRET, (err, user) => {
    if (err) {
      console.error('JWT verification error:', err.message);
      return res.status(403).json({ error: 'Invalid token' });
    }
    req.user = user;
    next();
  });
}

async function authenticateAdmin(req, res, next) {
  // Check if user is logged in via session instead of JWT
  if (!req.session || !req.session.login) {
    return res.status(401).json({ error: 'Authentication required' });
  }
  
  try {
    const user = await models.User.query().findById(req.session.user.id);
    
    if (!user.is_admin) {
      return res.status(403).json({ error: 'Admin access required' });
    }
    
    req.user = user;
    next();
  } catch (error) {
    console.error('Admin authentication error:', error);
    return res.status(500).json({ error: 'Internal server error' });
  }
}

module.exports = { authenticateToken, authenticateAdmin };