const baseModel = require("../../middleware/baseModel");
const logs = require("../../tool/logs_proxy");

/**
 * 记录审计（失败不影响主流程）
 */
async function logAudit(p) {
  try {
    await baseModel.biz_audit_log.create({
      admin_user_id: p.admin_user_id || null,
      biz_user_id: p.biz_user_id || null,
      action: p.action,
      resource_type: p.resource_type || "",
      resource_id: p.resource_id != null ? p.resource_id : null,
      detail: p.detail || null,
    });
  } catch (e) {
    logs.error("[biz_audit] 写入失败", e);
  }
}

function pickAdminId(ctx) {
  if (!ctx) return null;
  const u = ctx.user || ctx.state?.user || ctx.session?.user;
  if (u && (u.id != null || u.userId != null)) return u.id != null ? u.id : u.userId;
  return null;
}

module.exports = { logAudit, pickAdminId };
