import { z } from "zod";
import { createCrudFormError } from "@open-mercato/ui/backend/utils/serverErrors";
import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
import { CommunicationChannel } from "../data/entities.js";
import { getChannelAdapterRegistry } from "../lib/adapter-registry-singleton.js";
import { COMMUNICATION_CHANNELS_QUEUES, getCommunicationChannelsQueue } from "../lib/queue.js";
const queueImportHistorySchema = z.object({
  channelId: z.string().uuid(),
  sinceDays: z.number().int().min(1).max(365).default(30),
  contactEmails: z.array(z.string().email().max(255)).max(200).optional(),
  maxMessages: z.number().int().min(1).max(5e3).default(1e3)
});
const CHANNEL_IMPORT_HISTORY_JOB_TYPE = "communication_channels.channel.import_history";
async function queueImportHistory(params) {
  const input = queueImportHistorySchema.parse(params.input);
  const { container, scope } = params;
  const em = container.resolve("em").fork();
  const dscope = { tenantId: scope.tenantId, organizationId: scope.organizationId };
  const channel = await findOneWithDecryption(
    em,
    CommunicationChannel,
    {
      id: input.channelId,
      tenantId: scope.tenantId,
      organizationId: scope.organizationId,
      deletedAt: null
    },
    void 0,
    dscope
  );
  if (!channel) {
    throw createCrudFormError(
      "Channel not found",
      { channelId: "Channel not found" },
      { status: 404 }
    );
  }
  if (!channel.isActive || channel.status !== "connected") {
    throw createCrudFormError(
      "Channel is not connected",
      { channelId: "Channel must be connected to import history" },
      { status: 409 }
    );
  }
  const adapter = getChannelAdapterRegistry().get(channel.providerKey);
  if (!adapter) {
    throw createCrudFormError(
      "Channel provider is not available",
      { channelId: `No adapter registered for provider "${channel.providerKey}"` },
      { status: 400 }
    );
  }
  if (typeof adapter.importHistory !== "function") {
    throw createCrudFormError(
      "History import is not supported on this provider",
      { channelId: `Provider "${channel.providerKey}" does not support history import yet` },
      { status: 400 }
    );
  }
  const progressService = container.resolve("progressService");
  const progressContext = {
    tenantId: scope.tenantId,
    organizationId: scope.organizationId,
    userId: scope.userId ?? null
  };
  const active = await progressService.getActiveJobs(progressContext);
  const conflict = active.find((job) => {
    if (job.jobType !== CHANNEL_IMPORT_HISTORY_JOB_TYPE) return false;
    const meta = job.meta ?? {};
    return meta.channelId === channel.id;
  });
  if (conflict) {
    throw createCrudFormError(
      "An import is already in progress for this channel",
      { channelId: "Another history import is already running" },
      { status: 429 }
    );
  }
  const progressJob = await progressService.createJob(
    {
      jobType: CHANNEL_IMPORT_HISTORY_JOB_TYPE,
      name: `Import history: ${channel.displayName ?? channel.externalIdentifier ?? channel.providerKey}`,
      description: `Import up to ${input.maxMessages} messages from the last ${input.sinceDays} days`,
      totalCount: input.maxMessages,
      cancellable: true,
      meta: {
        channelId: channel.id,
        providerKey: channel.providerKey,
        sinceDays: input.sinceDays,
        contactEmailsCount: input.contactEmails?.length ?? 0,
        maxMessages: input.maxMessages
      }
    },
    progressContext
  );
  const payload = {
    progressJobId: progressJob.id,
    channelId: channel.id,
    sinceDays: input.sinceDays,
    contactEmails: input.contactEmails,
    maxMessages: input.maxMessages,
    scope: { tenantId: scope.tenantId, organizationId: scope.organizationId }
  };
  const queue = getCommunicationChannelsQueue(COMMUNICATION_CHANNELS_QUEUES.importHistory);
  await queue.enqueue(payload);
  return { progressJobId: progressJob.id, totalCountHint: input.maxMessages };
}
export {
  CHANNEL_IMPORT_HISTORY_JOB_TYPE,
  queueImportHistory,
  queueImportHistorySchema
};
//# sourceMappingURL=queue-import-history.js.map
