import { getGlobalHooks } from "../plugins/hook-system.js";
import { PatternUsageService } from "../services/pattern-usage.service.js";
import { scheduleAction } from "../scheduled-actions/scheduler.js";
import { entityRegistry } from "./registry.js";
function hasBlocksColumn(entityName) {
  var _a;
  try {
    const entityConfig = entityRegistry.get(entityName);
    return ((_a = entityConfig == null ? void 0 : entityConfig.builder) == null ? void 0 : _a.enabled) === true;
  } catch {
    return false;
  }
}
function extractBlocks(data) {
  if (!data || !("blocks" in data)) return [];
  const blocks = data.blocks;
  if (!Array.isArray(blocks)) return [];
  return blocks;
}
function initPatternUsageHooks() {
  const hooks = getGlobalHooks();
  hooks.addAction("entity.created", async (hookData) => {
    const data = hookData;
    const { entityName, data: entityData, userId } = data;
    if (!hasBlocksColumn(entityName)) return;
    if (entityName === "patterns") return;
    const entity = entityData;
    if (!(entity == null ? void 0 : entity.id) || !(entity == null ? void 0 : entity.teamId)) return;
    const blocks = extractBlocks(entity);
    if (blocks.length === 0) return;
    await PatternUsageService.syncUsages(
      entityName,
      String(entity.id),
      String(entity.teamId),
      blocks,
      userId || "system"
    );
  });
  hooks.addAction("entity.updated", async (hookData) => {
    const data = hookData;
    const { entityName, data: entityData, userId } = data;
    if (!hasBlocksColumn(entityName)) return;
    if (entityName === "patterns") return;
    const entity = entityData;
    if (!(entity == null ? void 0 : entity.id) || !(entity == null ? void 0 : entity.teamId)) return;
    const blocks = extractBlocks(entity);
    await PatternUsageService.syncUsages(
      entityName,
      String(entity.id),
      String(entity.teamId),
      blocks,
      userId || "system"
    );
  });
  hooks.addAction("entity.deleted", async (hookData) => {
    const data = hookData;
    const { entityName, id, userId } = data;
    if (!hasBlocksColumn(entityName)) return;
    if (entityName === "patterns") return;
    if (!id) return;
    await PatternUsageService.removeEntityUsages(
      entityName,
      id,
      userId || "system"
    );
  });
  hooks.addAction("entity.patterns.updated", async (hookData) => {
    const data = hookData;
    const { id, userId, data: entityData } = data;
    if (!id) return;
    const teamId = entityData == null ? void 0 : entityData.teamId;
    try {
      await scheduleAction(
        "pattern:invalidate-cache",
        { patternId: id, userId: userId || "system" },
        {
          scheduledAt: /* @__PURE__ */ new Date(),
          // Run immediately
          teamId
        }
      );
      console.info(`[PatternUsageHooks] Scheduled async cache invalidation for pattern ${id}`);
    } catch (error) {
      console.error(`[PatternUsageHooks] Error scheduling cache invalidation for pattern ${id}:`, error);
    }
  });
  console.log("[PatternUsageHooks] Initialized pattern usage tracking and cache invalidation hooks");
}
function isPatternUsageHooksInitialized() {
  const hooks = getGlobalHooks();
  return hooks.hasHook("entity.created");
}
export {
  initPatternUsageHooks,
  isPatternUsageHooksInitialized
};
