import { extractChangeRows, isRecord } from "./changeRows.js";
const ACTION_LOG_FILTER_TYPES = ["create", "edit", "delete", "assign"];
const ACTION_LOG_PROJECTION_TYPES = [...ACTION_LOG_FILTER_TYPES, "system"];
const ACTION_LOG_SOURCE_KEYS = ["ui", "api", "system"];
function normalizeText(value) {
  return (value ?? "").trim().toLowerCase();
}
function deriveActionLogActionType(input) {
  const normalizedCommandId = normalizeText(input.commandId);
  const normalizedLabel = normalizeText(input.actionLabel);
  if (normalizedCommandId.endsWith(".create") || normalizedCommandId.endsWith(".add") || normalizedLabel.includes("create") || normalizedLabel.includes("add")) {
    return "create";
  }
  if (normalizedCommandId.endsWith(".delete") || normalizedCommandId.endsWith(".remove") || normalizedLabel.includes("delete") || normalizedLabel.includes("remove")) {
    return "delete";
  }
  if (normalizedCommandId.endsWith(".assign") || normalizedCommandId.endsWith(".unassign") || normalizedLabel.includes("assign") || normalizedLabel.includes("unassign")) {
    return "assign";
  }
  if (normalizedCommandId.endsWith(".update") || normalizedCommandId.endsWith(".edit") || normalizedCommandId.endsWith(".upsert") || normalizedLabel.includes("update") || normalizedLabel.includes("edit") || normalizedLabel.includes("upsert")) {
    return "edit";
  }
  return "system";
}
function deriveActionLogSource(context, actorUserId) {
  const rawSource = isRecord(context) ? context.source : void 0;
  const normalizedSource = typeof rawSource === "string" ? rawSource.trim().toLowerCase() : "";
  if (normalizedSource === "api") return "api";
  if (normalizedSource === "system") return "system";
  if (normalizedSource === "ui") return "ui";
  return actorUserId ? "ui" : "system";
}
function deriveActionLogChangedFields(changes, snapshotBefore) {
  return Array.from(
    new Set(
      extractChangeRows(changes, snapshotBefore).map((entry) => entry.field).filter((value) => typeof value === "string" && value.trim().length > 0)
    )
  ).sort((left, right) => left.localeCompare(right));
}
function deriveActionLogProjection(input) {
  const changedFields = deriveActionLogChangedFields(input.changes, input.snapshotBefore);
  return {
    actionType: deriveActionLogActionType(input),
    changedFields,
    primaryChangedField: changedFields[0] ?? null,
    sourceKey: deriveActionLogSource(input.context, input.actorUserId)
  };
}
export {
  ACTION_LOG_FILTER_TYPES,
  ACTION_LOG_PROJECTION_TYPES,
  ACTION_LOG_SOURCE_KEYS,
  deriveActionLogActionType,
  deriveActionLogChangedFields,
  deriveActionLogProjection,
  deriveActionLogSource
};
//# sourceMappingURL=projections.js.map
