import { invalidateCrudCache } from "@open-mercato/shared/lib/crud/cache";
import { runWithCacheTenant } from "@open-mercato/cache";
import { createModuleQueue } from "@open-mercato/queue";
const CATALOG_PRODUCT_BULK_DELETE_QUEUE = "catalog-product-bulk-delete";
const queues = /* @__PURE__ */ new Map();
const BULK_DELETE_CACHE_ALIASES = ["catalog.products"];
function getCatalogQueue(queueName) {
  const existing = queues.get(queueName);
  if (existing) return existing;
  const concurrency = Math.max(1, Number.parseInt(process.env.CATALOG_QUEUE_CONCURRENCY ?? "3", 10) || 3);
  const created = createModuleQueue(queueName, { concurrency });
  queues.set(queueName, created);
  return created;
}
function buildCommandContext(scope, container) {
  return {
    container,
    auth: null,
    organizationScope: {
      selectedId: scope.organizationId,
      filterIds: [scope.organizationId],
      allowedIds: [scope.organizationId],
      tenantId: scope.tenantId
    },
    selectedOrganizationId: scope.organizationId,
    organizationIds: [scope.organizationId]
  };
}
async function deleteCatalogProductsWithProgress(params) {
  const { container, progressJobId, ids, scope } = params;
  const commandBus = container.resolve("commandBus");
  const progressService = container.resolve("progressService");
  const progressContext = {
    tenantId: scope.tenantId,
    organizationId: scope.organizationId,
    userId: scope.userId
  };
  await progressService.startJob(progressJobId, progressContext);
  await progressService.updateProgress(
    progressJobId,
    { totalCount: ids.length, processedCount: 0 },
    progressContext
  );
  const commandContext = buildCommandContext(scope, container);
  let affectedCount = 0;
  const deletedIds = /* @__PURE__ */ new Set();
  for (const [index, id] of ids.entries()) {
    await commandBus.execute("catalog.products.delete", {
      input: { body: { id } },
      ctx: commandContext,
      skipCacheInvalidation: true
    });
    affectedCount += 1;
    deletedIds.add(id);
    await progressService.updateProgress(
      progressJobId,
      {
        totalCount: ids.length,
        processedCount: index + 1
      },
      progressContext
    );
  }
  const summary = { affectedCount };
  await runWithCacheTenant(scope.tenantId, async () => {
    for (const id of deletedIds) {
      await invalidateCrudCache(
        container,
        "catalog.product",
        {
          id,
          organizationId: scope.organizationId,
          tenantId: scope.tenantId
        },
        scope.tenantId,
        "bulk-delete:catalog.products",
        BULK_DELETE_CACHE_ALIASES
      );
    }
  });
  await progressService.completeJob(progressJobId, { resultSummary: summary }, progressContext);
  return summary;
}
export {
  CATALOG_PRODUCT_BULK_DELETE_QUEUE,
  deleteCatalogProductsWithProgress,
  getCatalogQueue
};
//# sourceMappingURL=bulkDelete.js.map
