'use strict';

function requireAuth(req, res, next) {
  if (req.session?.user) return next();

  const wantsJson =
    req.path.startsWith('/auth/me') ||
    req.headers.accept?.includes('application/json') ||
    req.xhr;

  if (wantsJson) {
    return res.status(401).json({ error: 'Session expired. Please log in.', code: 'SESSION_EXPIRED' });
  }

  const next_ = encodeURIComponent(req.originalUrl);
  res.redirect(`/login.html?next=${next_}`);
}

function requireRole(...roles) {
  return (req, res, next) => {
    if (!req.session?.user) {
      return res.status(401).json({ error: 'Unauthorized.' });
    }
    if (!roles.includes(req.session.user.role)) {
      const wantsJson = req.headers.accept?.includes('application/json') || req.xhr;
      if (wantsJson) return res.status(403).json({ error: 'Insufficient permissions.' });
      return res.redirect('/403.html');
    }
    next();
  };
}

module.exports = { requireAuth, requireRole };
