const prisma = require("../prisma");

/**
 * Record an activity log entry (fire-and-forget safe when called without await in callers).
 */
async function logActivity({ userId, action, entityType, entityId, summary, metadata }) {
  try {
    await prisma.activityLog.create({
      data: {
        userId: userId || null,
        action,
        entityType,
        entityId: entityId || null,
        summary: summary || null,
        metadata: metadata ?? undefined,
      },
    });
  } catch (err) {
    console.error("[Audit] Failed to log activity:", err.message);
  }
}

function auditFromReq(req, payload) {
  const userId = req.user?.sub;
  logActivity({ userId, ...payload }).catch(() => {});
}

module.exports = { logActivity, auditFromReq };
