import {
  AUTHZED_PROJECTION_QUEUE_NAME,
  AUTHZED_RECONCILIATION_QUEUE_NAME,
  DATA_RETENTION_QUEUE_NAME,
  JOB_NAMES,
  type TJobsQueueName,
} from "@/src/constants";
import { type AnyBackgroundJobDefinition, toAnyBackgroundJobDefinition } from "@/src/contracts";
import { createMissingOverrideHandler } from "@/src/processors/missing-override";
import { type TGlobalScopeJobData, ZGlobalScopeJobData } from "@/src/types";

/**
 * The scope every recurring job runs under. It is both the scheduler-identity segment and the job
 * payload, which is why the two cannot drift.
 */
const GLOBAL_SCOPE = "global";

interface RecurringJobInput {
  /** Human-readable name used in log lines and error messages, e.g. "survey scheduling". */
  label: string;
  name: string;
  /**
   * A dedicated queue for the job, when it must never wait behind the default queue's work. Omitted means
   * the default `background-jobs`. Moving an existing job is safe: its handle retires the schedule left
   * on the default queue the next time it upserts (see `toRecurringJobHandle` in `queue.ts`).
   */
  queueName?: TJobsQueueName;
  /** Stable identity of the schedule in Redis. Changing it orphans the existing production schedule. */
  scheduleId: string;
}

export interface RecurringJobDescriptor {
  data: TGlobalScopeJobData;
  definition: AnyBackgroundJobDefinition;
  label: string;
  name: string;
  scheduleId: string;
  scope: string;
}

/**
 * Declares a recurring background job once, for both sides of the system: the worker registry (via
 * `definition`) and the producer that registers the schedule (via `name`/`scheduleId`/`scope`).
 *
 * What stays in `apps/web` is deliberate: the *timing* (cron pattern, interval, time zone — all
 * env-derived) and the real handler, which needs Prisma and app modules this package cannot import.
 * See `apps/web/lib/jobs/recurring-registrations.ts`.
 *
 * Handlers must be **idempotent and safe to overlap**: `BULLMQ_WORKER_CONCURRENCY` and
 * `BULLMQ_WORKER_COUNT` are operator-configurable and there may be several app replicas, so two ticks
 * of the same job can run at once. They must also stay I/O-bound — BullMQ renews the job lock on a
 * timer, so CPU-bound work that blocks the event loop is what makes a job stall, not a long runtime.
 */
export const defineRecurringJob = ({
  label,
  name,
  queueName,
  scheduleId,
}: RecurringJobInput): RecurringJobDescriptor => ({
  data: { scope: GLOBAL_SCOPE },
  definition: toAnyBackgroundJobDefinition({
    handle: createMissingOverrideHandler<TGlobalScopeJobData>(label, (data) => ({ scope: data.scope })),
    name,
    queueName,
    schema: ZGlobalScopeJobData,
  }),
  label,
  name,
  scheduleId,
  scope: GLOBAL_SCOPE,
});

/** Every recurring job in the system. Adding one here wires the registry, the producer and the exports. */
export const recurringJobDescriptors = {
  // Re-dispatches lost attachment exports, fails stale ones and deletes expired archives (ENG-6862).
  attachmentExportReconcile: defineRecurringJob({
    label: "attachment export reconcile",
    name: JOB_NAMES.attachmentExportReconcile,
    scheduleId: "attachment-export-reconcile",
  }),
  emailAuditMaintenance: defineRecurringJob({
    label: "email audit maintenance",
    name: JOB_NAMES.emailAuditMaintenance,
    scheduleId: "email-audit-maintenance",
  }),
  // Its own queue: a delivery stuck behind a long job (the nightly archive purge, a cleanup drain)
  // makes every authorization check fail closed.
  authzedProjectionDelivery: defineRecurringJob({
    label: "AuthZed projection delivery",
    name: JOB_NAMES.authzedProjectionDelivery,
    queueName: AUTHZED_PROJECTION_QUEUE_NAME,
    scheduleId: "authzed-projection-delivery",
  }),
  // Its own queue, shared with the survey audit: it walks every organization in one job and must not
  // hold up the default queue's jobs for the whole sweep.
  authzedReconciliationAudit: defineRecurringJob({
    label: "AuthZed reconciliation audit",
    name: JOB_NAMES.authzedReconciliationAudit,
    queueName: AUTHZED_RECONCILIATION_QUEUE_NAME,
    scheduleId: "authzed-reconciliation-audit",
  }),
  authzedSurveyAudit: defineRecurringJob({
    label: "AuthZed survey audit",
    name: JOB_NAMES.authzedSurveyAudit,
    queueName: AUTHZED_RECONCILIATION_QUEUE_NAME,
    scheduleId: "daily-authzed-survey-audit",
  }),
  // Copies creative counters from Redis to Postgres every minute (ENG-4000); idempotent by design.
  creativeStatsFlush: defineRecurringJob({
    label: "creative stats flush",
    name: JOB_NAMES.creativeStatsFlush,
    scheduleId: "creative-stats-flush",
  }),
  // Its own queue: it may run for half an hour, and must not hold up the default queue's jobs.
  dataRetentionSweep: defineRecurringJob({
    label: "data retention sweep",
    name: JOB_NAMES.dataRetentionSweep,
    queueName: DATA_RETENTION_QUEUE_NAME,
    scheduleId: "daily-data-retention-sweep",
  }),
  deletionCleanupDrain: defineRecurringJob({
    label: "deletion cleanup drain",
    name: JOB_NAMES.deletionCleanupDrain,
    scheduleId: "deletion-cleanup-drain",
  }),
  surveyArchivePurge: defineRecurringJob({
    label: "survey archive purge",
    name: JOB_NAMES.surveyArchivePurge,
    scheduleId: "daily-survey-archive-purge",
  }),
  surveyScheduling: defineRecurringJob({
    label: "survey scheduling",
    name: JOB_NAMES.surveyScheduling,
    scheduleId: "daily-survey-scheduling",
  }),
  usageTelemetry: defineRecurringJob({
    label: "usage telemetry",
    name: JOB_NAMES.usageTelemetry,
    scheduleId: "daily-usage-telemetry",
  }),
  workflowRunReconcile: defineRecurringJob({
    label: "workflow run reconcile",
    name: JOB_NAMES.workflowRunReconcile,
    scheduleId: "workflow-run-reconcile",
  }),
  // Clears workflow run content past its retention period, deletes old Test runs and stale samples
  // (ENG-7186, ADR 0044). Bounded per tick and idempotent.
  workflowRunRetention: defineRecurringJob({
    label: "workflow run retention",
    name: JOB_NAMES.workflowRunRetention,
    scheduleId: "workflow-run-retention",
  }),
  workflowsUsageSnapshot: defineRecurringJob({
    label: "workflows usage snapshot",
    name: JOB_NAMES.workflowsUsageSnapshot,
    scheduleId: "daily-workflows-usage-snapshot",
  }),
} as const satisfies Record<string, RecurringJobDescriptor>;

export type TRecurringJobKey = keyof typeof recurringJobDescriptors;

/** The recurring jobs' worker-side definitions, keyed by job name for `backgroundJobDefinitions`. */
export const recurringJobDefinitions: Record<string, AnyBackgroundJobDefinition> = Object.fromEntries(
  Object.values(recurringJobDescriptors).map((descriptor) => [descriptor.name, descriptor.definition])
);
