import { writeAuditLog } from "../utils/audit.js";

const ACTION_BY_METHOD = {
  POST: "add",
  PUT: "update",
  PATCH: "update",
  DELETE: "delete"
};

function cleanEntity(baseUrl = "") {
  return baseUrl.replace(/^\/api\//, "").replace(/\//g, ".") || "system";
}

export function auditMutationLogger(req, res, next) {
  const action = ACTION_BY_METHOD[req.method];
  if (!action) return next();

  res.on("finish", () => {
    if (res.statusCode >= 400) return;
    if (req.baseUrl.includes("/audit")) return;

    writeAuditLog(req, {
      action,
      entity: cleanEntity(req.baseUrl),
      entityId: req.params?.id || req.params?.customerId || null,
      details: {
        method: req.method,
        path: req.originalUrl,
        params: req.params || {},
        query: req.query || {}
      }
    });
  });

  next();
}
