import { recordIndexerError } from "@open-mercato/shared/lib/indexers/error-log";
import { recordIndexerLog } from "@open-mercato/shared/lib/indexers/status-log";
import { refreshCoverageSnapshot } from "../lib/coverage.js";
import { purgeIndexScope } from "../lib/purge.js";
const metadata = { event: "query_index.purge", persistent: true };
async function handle(payload, ctx) {
  const em = ctx.resolve("em");
  const entityType = String(payload?.entityType || "");
  if (!entityType) return;
  const orgId = payload?.organizationId ?? null;
  const tenantId = payload?.tenantId ?? null;
  try {
    await recordIndexerLog(
      { em },
      {
        source: "query_index",
        handler: "event:query_index.purge",
        message: `Purge started for ${entityType}`,
        entityType,
        tenantId,
        organizationId: orgId,
        details: { source: "event" }
      }
    );
    await purgeIndexScope(em, { entityType, organizationId: orgId, tenantId });
    try {
      await refreshCoverageSnapshot(
        em,
        {
          entityType,
          organizationId: orgId,
          tenantId,
          withDeleted: false
        }
      );
    } catch (refreshError) {
      await recordIndexerLog(
        { em },
        {
          source: "query_index",
          handler: "event:query_index.purge",
          level: "warn",
          message: `Coverage refresh failed after purge for ${entityType}`,
          entityType,
          tenantId,
          organizationId: orgId,
          details: {
            error: refreshError instanceof Error ? refreshError.message : String(refreshError)
          }
        }
      ).catch(() => void 0);
    }
    await recordIndexerLog(
      { em },
      {
        source: "query_index",
        handler: "event:query_index.purge",
        message: `Purge completed for ${entityType}`,
        entityType,
        tenantId,
        organizationId: orgId
      }
    );
  } catch (error) {
    await recordIndexerLog(
      { em },
      {
        source: "query_index",
        handler: "event:query_index.purge",
        level: "warn",
        message: `Purge failed for ${entityType}`,
        entityType,
        tenantId,
        organizationId: orgId,
        details: { error: error instanceof Error ? error.message : String(error) }
      }
    ).catch(() => void 0);
    await recordIndexerError(
      { em },
      {
        source: "query_index",
        handler: "event:query_index.purge",
        error,
        entityType,
        tenantId,
        organizationId: orgId,
        payload
      }
    );
    throw error;
  }
}
export {
  handle as default,
  metadata
};
//# sourceMappingURL=purge.js.map
