// utils/jwtUtils.js - JWT generation for Jitsi
const jwt = require('jsonwebtoken');

const generateJitsiJWT = (roomId, userName, isModerator, meetingId, expiryTime) => {
  const now = Math.floor(Date.now() / 1000);
  const exp = Math.floor(expiryTime.getTime() / 1000);
  
  const payload = {
    aud: 'jitsi',
    iss: process.env.JWT_ISSUER || 'meetings-192-168-1-33',
    sub: 'vpd.zrix.com', // Your IP domain
    room: roomId,
    exp: exp,
    nbf: now - 10,
    iat: now,
    context: {
      user: {
        id: meetingId.toString(),
        name: userName,
        moderator: isModerator,
        // avatar: `https://ui-avatars.com/api/?name=${encodeURIComponent(userName)}&background=0D8ABC&color=fff`
      },
      features: {
        livestreaming: false,
        recording: isModerator,
        transcription: false,
      }
    }
  };
  
  return jwt.sign(payload, process.env.JWT_SECRET, { algorithm: 'HS256' });
};

const validateJitsiJWT = (token) => {
  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET || 'your-secret-key');
    return { valid: true, payload: decoded };
  } catch (error) {
    return { valid: false, error: error.message };
  }
};

module.exports = {
  generateJitsiJWT,
  validateJitsiJWT
};
