const { queueAuditEvent } = require("./redis/dbSync.service")

function buildAuditMeta({ entityType, entityId, before = undefined, after = undefined, extra = undefined } = {}) {
  const meta = {}
  if (entityType) meta.entityType = entityType
  if (entityId !== undefined) meta.entityId = entityId
  if (before !== undefined) meta.before = before
  if (after !== undefined) meta.after = after
  if (extra !== undefined) meta.extra = extra
  return meta
}

function normalizeAuditMeta(meta) {
  if (!meta) return null
  if (typeof meta !== "object") return buildAuditMeta({ extra: meta })
  const entityType = meta.entityType
  const entityId = Object.prototype.hasOwnProperty.call(meta, "entityId") ? meta.entityId : undefined
  const before = Object.prototype.hasOwnProperty.call(meta, "before") ? meta.before : undefined
  const after = Object.prototype.hasOwnProperty.call(meta, "after") ? meta.after : undefined
  const extra = Object.prototype.hasOwnProperty.call(meta, "extra") ? meta.extra : undefined
  return buildAuditMeta({ entityType, entityId, before, after, extra })
}

function enqueueAuditEvent({ userId, action, ip, userAgent, meta = null }) {
  if (!userId || !action) return
  const normalizedMeta = normalizeAuditMeta(meta)
  queueAuditEvent({
    userId: Number(userId),
    action,
    ip,
    userAgent,
    meta: normalizedMeta,
  }).catch((err) => console.error("Audit enqueue failed:", err?.message || err))
}

function enqueueAuditFromRequest(req, action, meta = null) {
  if (!req?.auth?.userId) return
  enqueueAuditEvent({
    userId: req.auth.userId,
    action,
    ip: req.ip,
    userAgent: req.headers["user-agent"] || null,
    meta,
  })
}

module.exports = {
  enqueueAuditEvent,
  enqueueAuditFromRequest,
  buildAuditMeta,
}
