import {
  COMMUNICATION_CHANNELS_INGEST_INBOUND_COMMAND_ID
} from "../commands/ingest-inbound-message.js";
import { COMMUNICATION_CHANNELS_QUEUES } from "../lib/queue.js";
const metadata = {
  queue: COMMUNICATION_CHANNELS_QUEUES.inbound,
  id: "communication_channels:inbound-processor",
  concurrency: 10
};
async function handle(job, ctx) {
  const { providerKey, channelId, channelType, raw, scope } = job.payload;
  const adapterRegistry = ctx.resolve("channelAdapterRegistry");
  const adapter = adapterRegistry?.get(providerKey);
  if (!adapter) {
    throw new Error(
      `No ChannelAdapter registered for providerKey '${providerKey}' (worker job ${job.id}). Check that the provider package is enabled in modules.ts.`
    );
  }
  const normalized = await adapter.normalizeInbound(raw);
  if (!normalized?.externalMessageId || !normalized?.externalConversationId) {
    throw new Error(
      `Adapter '${providerKey}' returned a normalized message missing required fields (externalMessageId, externalConversationId) for worker job ${job.id}`
    );
  }
  const commandBus = ctx.resolve("commandBus");
  const containerProxy = { resolve: ctx.resolve.bind(ctx) };
  const commandCtx = {
    container: containerProxy,
    auth: null,
    organizationScope: null,
    selectedOrganizationId: scope.organizationId ?? null,
    organizationIds: scope.organizationId ? [scope.organizationId] : null
  };
  const input = {
    channelId,
    providerKey,
    channelType,
    scope,
    message: normalized
  };
  const { result } = await commandBus.execute(
    COMMUNICATION_CHANNELS_INGEST_INBOUND_COMMAND_ID,
    {
      input,
      ctx: commandCtx
    }
  );
  if (result.status === "duplicate") {
    return;
  }
}
export {
  handle as default,
  metadata
};
//# sourceMappingURL=inbound-processor.js.map
