const prisma = require("../models/prisma");
const logger = require("../utils/logger");

const auditLog = (action, entity) => {
  return async (req, res, next) => {
    const originalJson = res.json.bind(res);
    res.json = async (data) => {
      if (res.statusCode >= 200 && res.statusCode < 300) {
        try {
          await prisma.auditLog.create({
            data: {
              userId: req.user?.id || null,
              action,
              entity,
              entityId: req.params?.id || data?.id || null,
              newValues: data || null,
              ipAddress: req.ip,
              userAgent: req.headers["user-agent"],
            },
          });
        } catch (err) {
          logger.error("Error guardando audit log:", err);
        }
      }
      return originalJson(data);
    };
    next();
  };
};

module.exports = { auditLog };
