function requireAuth(req, res, next) {
  const signed = !!process.env.COOKIE_SECRET;
  const raw = signed ? req.signedCookies.emby_user : req.cookies.emby_user;
  if (!raw || raw === false) {
    return res.status(401).json({ error: 'Not authenticated' });
  }
  let u;
  try {
    u = JSON.parse(raw);
  } catch {
    return res.status(401).json({ error: 'Invalid session' });
  }
  // Schema validation
  if (typeof u.id !== 'string' || !u.id) return res.status(401).json({ error: 'Invalid session' });
  if (typeof u.name !== 'string' || !u.name) return res.status(401).json({ error: 'Invalid session' });
  if (typeof u.isAdmin !== 'boolean') u.isAdmin = !!u.isAdmin;
  req.user = u;
  next();
}

module.exports = requireAuth;
