const jwt = require('jsonwebtoken');
const db = require('../config/database');

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

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

  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    
    // Only check session for parent users, others use standard JWT
    if (decoded.role === 'parent') {
      const [sessions] = await db.execute(
        'SELECT 1 FROM user_sessions WHERE jwt_token = ? AND user_id = ? LIMIT 1',
        [token, decoded.id]
      );
      
      if (sessions.length === 0) {
        return res.status(401).json({ message: 'Session expired or invalid' });
      }
    }
    
    req.user = decoded;
    next();
  } catch (err) {
    return res.status(403).json({ message: 'Invalid token' });
  }
};

const authorizeRole = (roles) => {
  return (req, res, next) => {
    if (!roles.includes(req.user.role)) {
      return res.status(403).json({ message: 'Access denied' });
    }
    next();
  };
};

module.exports = { authenticateToken, authorizeRole };