import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
import { SyncSchedule } from "../data/entities.js";
import { startDataSyncRun } from "../lib/start-run.js";
const metadata = {
  queue: "data-sync-scheduled",
  id: "data-sync:scheduled",
  concurrency: 3
};
async function handle(job, ctx) {
  const em = ctx.resolve("em");
  const syncRunService = ctx.resolve("dataSyncRunService");
  const progressService = ctx.resolve("progressService");
  const integrationStateService = ctx.resolve("integrationStateService");
  const schedule = await findOneWithDecryption(
    em,
    SyncSchedule,
    {
      id: job.payload.scheduleId,
      organizationId: job.payload.scope.organizationId,
      tenantId: job.payload.scope.tenantId,
      deletedAt: null
    },
    void 0,
    job.payload.scope
  );
  if (!schedule || !schedule.isEnabled) {
    return;
  }
  const integrationEnabled = await integrationStateService.isEnabled(schedule.integrationId, job.payload.scope);
  if (!integrationEnabled) {
    return;
  }
  const overlap = await syncRunService.findRunningOverlap(
    schedule.integrationId,
    schedule.entityType,
    schedule.direction,
    job.payload.scope
  );
  if (overlap) {
    return;
  }
  const cursor = schedule.fullSync ? null : await syncRunService.resolveCursor(
    schedule.integrationId,
    schedule.entityType,
    schedule.direction,
    job.payload.scope
  );
  schedule.lastRunAt = /* @__PURE__ */ new Date();
  await em.flush();
  await startDataSyncRun({
    syncRunService,
    progressService,
    scope: job.payload.scope,
    input: {
      integrationId: schedule.integrationId,
      entityType: schedule.entityType,
      direction: schedule.direction,
      cursor,
      triggeredBy: "scheduler"
    }
  });
}
export {
  handle as default,
  metadata
};
//# sourceMappingURL=sync-scheduled.js.map
