/**
 * Auth middleware — requires user session for protected routes.
 * Public: landing page, auth routes, static assets, health, placeholder API.
 */

const PUBLIC_PATHS = ['/', '/health', '/favicon.ico', '/status', '/placeholder'];
const PUBLIC_API = ['/api/settings', '/api/tools', '/api/content/advantages', '/api/content/dashboard'];
const PUBLIC_PREFIXES = ['/auth/', '/vendor/', '/placeholder-img/', '/status/'];
const PUBLIC_FILES = ['/shared.css', '/shared.js', '/landing.html'];

function authMiddleware(req, res, next) {
  // Public paths
  if (PUBLIC_PATHS.includes(req.path)) return next();
  if (PUBLIC_API.includes(req.path)) return next();
  if (PUBLIC_FILES.includes(req.path)) return next();
  if (PUBLIC_PREFIXES.some(p => req.path.startsWith(p))) return next();

  // Authenticated user
  if (req.session && req.session.user) return next();

  // API requests — 401 JSON
  if (req.path.startsWith('/api/') || req.path.startsWith('/download/')) {
    return res.status(401).json({ error: 'Unauthorized' });
  }

  // Page requests — save return URL and redirect to login
  if (req.method === 'GET') {
    req.session.returnTo = req.originalUrl;
    return res.redirect('/auth/login');
  }

  return res.status(401).json({ error: 'Unauthorized' });
}

module.exports = authMiddleware;
