import { sql } from "kysely";
import { createLogger } from "../logger/index.js";
const logger = createLogger("shared").child({ component: "indexers" });
const MAX_MESSAGE_LENGTH = 8192;
const MAX_STACK_LENGTH = 32768;
function truncate(input, limit) {
  if (!input) return null;
  return input.length > limit ? `${input.slice(0, limit - 3)}...` : input;
}
function normalizeError(error) {
  if (error instanceof Error) {
    return {
      message: error.message || error.name || "Unknown error",
      stack: typeof error.stack === "string" ? error.stack : null
    };
  }
  if (typeof error === "string") {
    return { message: error, stack: null };
  }
  try {
    const json = JSON.stringify(error);
    return { message: json, stack: null };
  } catch {
    return { message: String(error ?? "Unknown error"), stack: null };
  }
}
function safeJson(value) {
  if (value === void 0) return null;
  try {
    return JSON.parse(JSON.stringify(value));
  } catch {
    if (value == null) return null;
    if (typeof value === "object") {
      return { note: "unserializable", asString: String(value) };
    }
    return value;
  }
}
function pickDb(deps) {
  if (deps.db) return deps.db;
  if (deps.em) {
    try {
      return deps.em.getKysely();
    } catch {
      return null;
    }
  }
  return null;
}
async function recordIndexerError(deps, input) {
  const db = pickDb(deps);
  if (!db) {
    logger.error("Unable to record indexer error (missing db connection)", {
      source: input.source,
      handler: input.handler
    });
    return;
  }
  const { message, stack } = normalizeError(input.error);
  const payload = safeJson(input.payload);
  const now = /* @__PURE__ */ new Date();
  logger.error("Indexer error recorded", {
    source: input.source,
    handler: input.handler,
    entityType: input.entityType ?? null,
    recordId: input.recordId ?? null,
    tenantId: input.tenantId ?? null,
    organizationId: input.organizationId ?? null,
    err: input.error
  });
  try {
    await db.insertInto("indexer_error_logs").values({
      source: input.source,
      handler: input.handler,
      entity_type: input.entityType ?? null,
      record_id: input.recordId ?? null,
      tenant_id: input.tenantId ?? null,
      organization_id: input.organizationId ?? null,
      payload: payload === null ? null : sql`${JSON.stringify(payload)}::jsonb`,
      message: truncate(message, MAX_MESSAGE_LENGTH),
      stack: truncate(stack, MAX_STACK_LENGTH),
      occurred_at: now
    }).execute();
  } catch (loggingError) {
    logger.error("Failed to persist indexer error", { err: loggingError });
  }
}
export {
  recordIndexerError
};
//# sourceMappingURL=error-log.js.map
