const { logger } = require('./logger');

/**
 * Middleware that blocks guest users from accessing non-abonnement routes.
 * Guest users (role='guest') can ONLY access:
 *   - /abonements/*
 *   - /invoices/mine
 *   - /me
 *   - /user/settings
 *   - /logout
 *   - /refresh
 *
 * Place this AFTER authMiddleware in the app-level middleware chain.
 */
const GUEST_ALLOWED_PREFIXES = [
  '/abonements',
  '/invoices/mine',
  '/me',
  '/user/settings',
  '/user/status',
  '/logout',
  '/refresh',
  '/coffee/active',
  '/tax/vat-rates',
  '/send-verification-email',
  '/verify-email-code',
];

function guestRestriction(req, res, next) {
  const user = req.user;
  if (!user || user.role !== 'guest') {
    return next();
  }

  const urlPath = req.originalUrl.split('?')[0];
  // Strip /api prefix if present (routes are mounted at /api but prefixes listed without it)
  const normalizedPath = urlPath.startsWith('/api/') ? urlPath.slice(4) : urlPath;

  const isAllowed = GUEST_ALLOWED_PREFIXES.some((prefix) => normalizedPath.startsWith(prefix));

  // Allow guests to fetch their own permissions
  const userId = user.userId || user.id;
  const isOwnPermissions = userId && normalizedPath === `/users/${userId}/permissions`;

  if (isAllowed || isOwnPermissions) {
    return next();
  }

  logger.warn('guestRestriction:blocked', {
    userId: user.userId || user.id,
    route: urlPath,
    method: req.method,
  });

  return res.status(403).json({
    success: false,
    message: 'Guest accounts can only access subscription features. Please upgrade your account for full access.',
  });
}

module.exports = guestRestriction;
