const logger = require("../config/logger");
const { sendUnauthorized, sendForbidden } = require("../utils/responseHelpers");

const isAuthenticated = (req) => {
  return req.session?.user?.id;
};

const requireAuth = (req, res, next) => {
  if (isAuthenticated(req)) {
    return next();
  }

  logger.warn("Unauthorized access attempt", {
    path: req.path,
    ip: req.ip,
  });
  sendUnauthorized(res);
};

const requireRole = (allowedRoles) => {
  const roles = Array.isArray(allowedRoles) ? allowedRoles : [allowedRoles];

  return (req, res, next) => {
    if (!isAuthenticated(req)) {
      logger.warn("Unauthorized access attempt", {
        path: req.path,
        ip: req.ip,
      });
      return sendUnauthorized(res);
    }

    const userRole = req.session.user.role_id || "role-admin";

    if (roles.includes(userRole)) {
      return next();
    }

    logger.warn("Forbidden access attempt", {
      path: req.path,
      ip: req.ip,
      userRole,
      requiredRoles: roles,
    });

    sendForbidden(res, "Access denied. Insufficient permissions.");
  };
};

module.exports = { requireAuth, requireRole };
