const { AuditLog } = require("../models");

const audit =  (action, entityType) => {
  return async function (req, res, next) {
    const startedAt = Date.now();
    const adminId = req.admin?.id ?? null;

    res.on("finish", async () => {
      try {
        const entityId =
          req.params?.userId ||
          req.params?.walletId ||
          req.params?.depositId ||
          req.params?.withdrawalId ||
          req.params?.txId ||
          req.params?.copyTraderId ||
          req.params?.key ||
          null;

        await AuditLog.create({
          adminId,
          action,
          entityType,
          entityId,
          statusCode: res.statusCode,
          ip: req.ip,
          userAgent: req.headers["user-agent"] || null,
          requestBody: req.body || {},
          requestParams: req.params || {},
          requestQuery: req.query || {},
          durationMs: Date.now() - startedAt,
        });
      } catch (e) {
        // never block due to audit failure
      }
    });

    next();
  };
}
module.exports = {
    audit
}
