import { revalidatePath } from "next/cache";
import { registerScheduledAction } from "../registry.js";
import { PatternUsageService } from "../../services/pattern-usage.service.js";
import { entityRegistry } from "../../entities/registry.js";
import { getEntityBasePath } from "../../entities/schema-generator.js";
function getEntityPublicUrl(entityType, entitySlug) {
  var _a;
  if (!entitySlug) return null;
  try {
    const entityConfig = entityRegistry.get(entityType);
    if (!entityConfig) return null;
    if (((_a = entityConfig.access) == null ? void 0 : _a.public) === false) return null;
    const basePath = getEntityBasePath(entityConfig);
    if (basePath === "/") {
      return `/${entitySlug}`;
    } else if (basePath) {
      return `${basePath}/${entitySlug}`;
    }
    return `/${entityType}/${entitySlug}`;
  } catch {
    return null;
  }
}
function registerPatternCacheInvalidationHandler() {
  registerScheduledAction(
    "pattern:invalidate-cache",
    async (payload, action) => {
      const { patternId, userId } = payload;
      console.info(
        `[ScheduledAction:pattern:invalidate-cache] Starting for pattern ${patternId} (action: ${action.id})`
      );
      const MAX_USAGES = 1e3;
      const { usages, total } = await PatternUsageService.getUsagesWithEntityInfo(
        patternId,
        userId,
        { limit: MAX_USAGES }
      );
      if (total === 0) {
        console.info(
          `[ScheduledAction:pattern:invalidate-cache] Pattern ${patternId} has no usages, nothing to invalidate`
        );
        return;
      }
      if (total > MAX_USAGES) {
        console.warn(
          `[ScheduledAction:pattern:invalidate-cache] Pattern ${patternId} has ${total} usages, only invalidating first ${MAX_USAGES}. Remaining pages will refresh via ISR.`
        );
      }
      const invalidatedPaths = [];
      const BATCH_SIZE = 10;
      for (let i = 0; i < usages.length; i += BATCH_SIZE) {
        const batch = usages.slice(i, i + BATCH_SIZE);
        await Promise.all(
          batch.map(async (usage) => {
            const publicUrl = getEntityPublicUrl(usage.entityType, usage.entitySlug);
            if (publicUrl) {
              try {
                revalidatePath(publicUrl);
                invalidatedPaths.push(publicUrl);
              } catch (error) {
                console.warn(
                  `[ScheduledAction:pattern:invalidate-cache] Failed to revalidate ${publicUrl}:`,
                  error
                );
              }
            }
          })
        );
      }
      console.info(
        `[ScheduledAction:pattern:invalidate-cache] Pattern ${patternId}: Invalidated ${invalidatedPaths.length}/${total} pages. Sample paths: ${invalidatedPaths.slice(0, 5).join(", ")}${invalidatedPaths.length > 5 ? "..." : ""}`
      );
    },
    {
      description: "Invalidate ISR cache for pages using a pattern",
      timeout: 3e4
      // 30 seconds timeout for large invalidations
    }
  );
  console.log("[ScheduledActions] Registered handler: pattern:invalidate-cache");
}
export {
  registerPatternCacheInvalidationHandler
};
