const jwt = require('jsonwebtoken');
const { getPool } = require('../config/database');

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

  if (!token) {
    return res.status(401).json({
      success: false,
      error: 'Access token required'
    });
  }

  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    
    // Check if token exists in database
    const pool = getPool();
    const [sessions] = await pool.execute(
      'SELECT * FROM user_sessions WHERE token = ? AND expires_at > NOW()',
      [token]
    );

    if (sessions.length === 0) {
      return res.status(401).json({
        success: false,
        error: 'Invalid or expired token'
      });
    }

    // Get player data (decoded.userId is citizenid)
    const [players] = await pool.execute(
      'SELECT citizenid, user, gmail, active FROM players WHERE citizenid = ?',
      [decoded.userId]
    );

    if (players.length === 0) {
      return res.status(401).json({
        success: false,
        error: 'User not found'
      });
    }

    const player = players[0];
    req.user = {
      id: player.citizenid,
      username: player.user,
      email: player.gmail,
      is_verified: player.active === 1
    };
    req.token = token;
    next();
  } catch (error) {
    console.error('Token verification failed:', error);
    return res.status(403).json({
      success: false,
      error: 'Invalid token'
    });
  }
};

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

  if (!token) {
    return next();
  }

  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    
    const pool = getPool();
    const [sessions] = await pool.execute(
      'SELECT * FROM user_sessions WHERE token = ? AND expires_at > NOW()',
      [token]
    );

    if (sessions.length > 0) {
      const [players] = await pool.execute(
        'SELECT citizenid, user, gmail, active FROM players WHERE citizenid = ?',
        [decoded.userId]
      );

      if (players.length > 0) {
        const player = players[0];
        req.user = {
          id: player.citizenid,
          username: player.user,
          email: player.gmail,
          is_verified: player.active === 1
        };
        req.token = token;
      }
    }
  } catch (error) {
    // Ignore token errors for optional auth
  }

  next();
};

module.exports = {
  authenticateToken,
  optionalAuth
}; 