'use strict';

const logger = require('../utils/logger');
const securityStore = require('../security/securityStore');

function hasPermission(req, permissionCode) {
  return securityStore.hasPermission(req.user, permissionCode);
}

function requirePermission(permissionCode) {
  return (req, res, next) => {
    if (hasPermission(req, permissionCode)) return next();
    securityStore.audit('permission_denied', {
      permission: permissionCode,
      user_id: req.user?.id || req.user?.rol || req.user?.tipo || 'anonymous',
      path: req.originalUrl || req.path,
      ip: req.ip,
    });
    logger.warn({
      event: 'permission_denied',
      permission: permissionCode,
      user: req.user?.id || req.user?.rol || req.user?.tipo || 'anonymous',
      path: req.originalUrl || req.path,
      ip: req.ip,
    });
    return res.status(403).json({ ok: false, code: 'permission_denied', permission: permissionCode, error: 'No tienes permiso.' });
  };
}

module.exports = { hasPermission, requirePermission };
