var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/modules/ScanOrderLogger/providers/feishu.ts
var feishu_exports = {};
__export(feishu_exports, {
  feishuLoggerProvider: () => feishuLoggerProvider
});
module.exports = __toCommonJS(feishu_exports);
var DEFAULT_THROTTLE_MS = 3e3;
var pendingQueue = [];
var flushTimer = null;
var cachedProviderConfig;
function safeStringify(value) {
  if (value === void 0 || value === null)
    return "";
  if (typeof value === "string")
    return value;
  if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
    return String(value);
  }
  try {
    return JSON.stringify(value);
  } catch (error) {
    return `[unserializable: ${String(error)}]`;
  }
}
function isWebhookUsable(webhook) {
  if (!webhook)
    return false;
  if (webhook.includes("REPLACE_ME"))
    return false;
  return true;
}
function buildRecordSegments(record) {
  const context = record.context || {};
  return [
    [{ tag: "text", text: `[${record.level}] ${record.timestamp} ${record.title}
` }],
    [{ tag: "text", text: `缓存标识: ${safeStringify(context.cacheId)}
` }],
    [{ tag: "text", text: `日志来源: ${safeStringify(context)}
` }],
    [{ tag: "text", text: `日志内容: ${safeStringify(record.payload)}
` }],
    [{ tag: "text", text: `扩展信息: ${safeStringify(record.extra)}
` }],
    [{ tag: "text", text: "------\n" }]
  ];
}
function buildFeishuBody(records) {
  const title = records.length === 1 ? records[0].title : `ScanOrder 日志批量 (${records.length} 条)`;
  const content = [];
  records.forEach((record) => {
    buildRecordSegments(record).forEach((segment) => content.push(segment));
  });
  return JSON.stringify({
    msg_type: "post",
    content: JSON.stringify({
      post: {
        zh_cn: {
          title,
          content
        }
      }
    })
  });
}
async function postToFeishu(webhook, body) {
  await fetch(webhook, {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body
  });
}
async function flushQueue() {
  var _a;
  flushTimer = null;
  if (!pendingQueue.length)
    return;
  const records = pendingQueue.splice(0, pendingQueue.length);
  const webhook = (_a = cachedProviderConfig == null ? void 0 : cachedProviderConfig.feishu) == null ? void 0 : _a.webhook;
  if (!isWebhookUsable(webhook)) {
    return;
  }
  if (typeof fetch !== "function") {
    console.warn("[ScanOrderLogger] 当前环境不支持 fetch，跳过 Feishu 日志批量上报");
    return;
  }
  try {
    await postToFeishu(webhook, buildFeishuBody(records));
  } catch (error) {
    console.warn("[ScanOrderLogger] Feishu 批量上报失败", error);
  }
}
var feishuLoggerProvider = {
  async send(payload) {
    var _a, _b, _c, _d;
    cachedProviderConfig = payload.providerConfig;
    const webhook = (_b = (_a = payload.providerConfig) == null ? void 0 : _a.feishu) == null ? void 0 : _b.webhook;
    if (!webhook) {
      console.warn("[ScanOrderLogger] Feishu webhook 未配置，跳过日志上报");
      return;
    }
    if (!isWebhookUsable(webhook))
      return;
    if (typeof fetch !== "function") {
      console.warn("[ScanOrderLogger] 当前环境不支持 fetch，跳过 Feishu 日志上报");
      return;
    }
    const throttleMs = ((_d = (_c = payload.providerConfig) == null ? void 0 : _c.feishu) == null ? void 0 : _d.throttleMs) ?? DEFAULT_THROTTLE_MS;
    if (throttleMs <= 0) {
      try {
        await postToFeishu(webhook, buildFeishuBody([payload.record]));
      } catch (error) {
        console.warn("[ScanOrderLogger] Feishu 日志上报失败", error);
      }
      return;
    }
    pendingQueue.push(payload.record);
    if (!flushTimer) {
      flushTimer = setTimeout(() => {
        void flushQueue();
      }, throttleMs);
    }
  }
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  feishuLoggerProvider
});
