// Shared GM authorization middleware
// Authorizes based on server-side session lookup via x-session-id header.
// Does NOT trust x-gm-secret header (that was the vulnerability).
//
// Usage in async route handlers:
//   const { requireGM } = require('../auth');
//   if (!(await requireGM(req, res))) return;
//
// Usage in sync middleware (not supported — this is async only).

const { validateSession } = require('./sessionModel');

async function requireGM(req, res) {
  const sessionId = req.headers['x-session-id'];
  if (!sessionId) {
    res.status(401).json({ error: 'Authentication required' });
    return false;
  }

  const session = await validateSession(sessionId);
  if (!session || !session.data || !session.data.playerName) {
    res.status(401).json({ error: 'Invalid or expired session' });
    return false;
  }

  if (session.data.playerName.toLowerCase() !== 'gm') {
    res.status(403).json({ error: 'GM access required' });
    return false;
  }

  return true;
}

module.exports = { requireGM };