import { findWithDecryption } from "@open-mercato/shared/lib/encryption/find";
import { CommunicationChannel } from "../data/entities.js";
import { COMMUNICATION_CHANNELS_QUEUES } from "../lib/queue.js";
import { pushRenew } from "../commands/push-renew.js";
import { emitCommunicationChannelsEvent } from "../events.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("communication_channels").child({ component: "gmail-renew-watch" });
const metadata = {
  queue: COMMUNICATION_CHANNELS_QUEUES.gmailRenewWatch,
  id: "communication_channels:gmail-renew-watch",
  concurrency: 1
};
const LEAD_HOURS = Math.max(
  1,
  Number.parseInt(process.env.OM_PUSH_RENEWAL_GMAIL_LEAD_HOURS ?? "24", 10) || 24
);
async function handle(job, ctx) {
  const em = ctx.resolve("em").fork();
  const cutoffMs = Date.now() + LEAD_HOURS * 60 * 60 * 1e3;
  const scope = job?.payload?.scope ?? null;
  const where = {
    providerKey: "gmail",
    isActive: true,
    deletedAt: null
  };
  if (scope?.tenantId) where.tenantId = scope.tenantId;
  if (scope?.organizationId) where.organizationId = scope.organizationId;
  const channels = await findWithDecryption(
    em,
    CommunicationChannel,
    where,
    void 0,
    scope ? { tenantId: scope.tenantId, organizationId: scope.organizationId ?? null } : void 0
  );
  const containerProxy = ctx.container;
  let renewed = 0;
  let failed = 0;
  for (const channel of channels) {
    const state = channel.channelState ?? null;
    if (!state || state.pushStatus !== "active") continue;
    if (typeof state.watchExpirationMs !== "number") continue;
    if (state.watchExpirationMs > cutoffMs) continue;
    const organizationId = channel.organizationId;
    if (!organizationId) {
      logger.warn("skipping channel \u2014 no organizationId on row", { channelId: channel.id });
      continue;
    }
    try {
      const container = resolveContainer(containerProxy, ctx);
      const result = await pushRenew({
        container,
        scope: {
          tenantId: channel.tenantId,
          organizationId,
          userId: channel.userId ?? null
        },
        input: { channelId: channel.id }
      });
      if (result.pushStatus === "active") {
        renewed += 1;
        await emitCommunicationChannelsEvent(
          "communication_channels.push.renewed",
          {
            channelId: channel.id,
            providerKey: channel.providerKey,
            tenantId: channel.tenantId,
            organizationId
          },
          { persistent: false }
        );
      } else {
        failed += 1;
      }
    } catch (err) {
      failed += 1;
      logger.warn("failed to renew channel watch", { channelId: channel.id, err });
    }
  }
  if (renewed > 0 || failed > 0) {
    logger.info("gmail watch renewal summary", { renewed, failed });
  }
}
function resolveContainer(containerProxy, ctx) {
  if (containerProxy && typeof containerProxy === "object" && "resolve" in containerProxy) {
    return containerProxy;
  }
  return { resolve: ctx.resolve.bind(ctx) };
}
export {
  handle as default,
  metadata
};
//# sourceMappingURL=gmail-renew-watch.js.map
