const jwt = require('jsonwebtoken');

// JWT Secret HARUS dari environment variable — tidak boleh ada fallback hardcoded
const JWT_SECRET = process.env.JWT_SECRET;
if (!JWT_SECRET) {
  console.error('❌ FATAL: JWT_SECRET tidak ditemukan di environment variables!');
  console.error('   Tambahkan JWT_SECRET di file .env');
  process.exit(1);
}

function auth(roles = []) {
  return (req, res, next) => {
    const token = req.headers.authorization?.split(' ')[1];
    if (!token) return res.status(401).json({ success: false, message: 'Token tidak ditemukan' });
    try {
      const decoded = jwt.verify(token, JWT_SECRET);
      req.user = decoded;
      if (roles.length && !roles.includes(decoded.role)) {
        return res.status(403).json({ success: false, message: 'Akses ditolak' });
      }
      next();
    } catch {
      return res.status(401).json({ success: false, message: 'Token tidak valid' });
    }
  };
}

function createSessionToken(email) {
  return jwt.sign({ email, type: 'konsultasi-session' }, JWT_SECRET, { expiresIn: '24h' });
}

function verifySessionToken(token) {
  try {
    const decoded = jwt.verify(token, JWT_SECRET);
    if (decoded.type !== 'konsultasi-session') return null;
    return decoded;
  } catch { return null; }
}

module.exports = { auth, createSessionToken, verifySessionToken, JWT_SECRET };
