/**
 * Durable job queue on Postgres (NFR-007/008): syncs, journeys, webhooks and sends run as jobs so a slow
 * provider never blocks the app. Drained by /api/cron/worker (Vercel Cron) and opportunistically via after().
 * Failed jobs retry with exponential backoff; exhausted jobs go to the dead-letter state and can be replayed.
 */
import { and, eq, inArray, lte, sql } from "drizzle-orm";
import { getDb, schema, type DB } from "@/db";

export type JobHandler = (payload: Record<string, unknown>, job: typeof schema.jobs.$inferSelect) => Promise<void>;
const handlers = new Map<string, JobHandler>();

export function registerJob(type: string, h: JobHandler) {
  handlers.set(type, h);
}

export async function enqueue(db: DB, type: string, payload: Record<string, unknown>, opts: { workspaceId?: string | null; runAt?: Date; idempotencyKey?: string; maxAttempts?: number } = {}) {
  const rows = await db.insert(schema.jobs).values({
    type, payload,
    workspaceId: opts.workspaceId ?? (payload.workspaceId as string | undefined) ?? null,
    runAt: opts.runAt ?? new Date(),
    idempotencyKey: opts.idempotencyKey ?? null,
    maxAttempts: opts.maxAttempts ?? 8,
  }).onConflictDoNothing().returning({ id: schema.jobs.id });
  return rows[0]?.id ?? null;
}

let draining: Promise<number> | null = null;

/** Claim and run due jobs. Returns number processed. Safe to call concurrently (row claim is atomic). */
export async function runJobs(limit = 25, budgetMs = 20000): Promise<number> {
  if (draining) return draining;
  draining = (async () => {
    await import("./job-handlers"); // registers handlers
    const db = await getDb();
    const started = Date.now();
    let done = 0;
    // recover stuck jobs (worker died mid-run)
    await db.update(schema.jobs).set({ status: "queued", lockedAt: null })
      .where(and(eq(schema.jobs.status, "running"), lte(schema.jobs.lockedAt, new Date(Date.now() - 5 * 60000))));
    while (done < limit && Date.now() - started < budgetMs) {
      const due = await db.select({ id: schema.jobs.id }).from(schema.jobs)
        .where(and(eq(schema.jobs.status, "queued"), lte(schema.jobs.runAt, new Date())))
        .orderBy(schema.jobs.runAt).limit(5);
      if (!due.length) break;
      const claimed = await db.update(schema.jobs).set({ status: "running", lockedAt: new Date(), attempts: sql`${schema.jobs.attempts} + 1`, updatedAt: new Date() })
        .where(and(inArray(schema.jobs.id, due.map((d) => d.id)), eq(schema.jobs.status, "queued"))).returning();
      for (const job of claimed) {
        const h = handlers.get(job.type);
        try {
          if (!h) throw new Error(`No handler for job type ${job.type}`);
          await h(job.payload, job);
          await db.update(schema.jobs).set({ status: "done", lockedAt: null, updatedAt: new Date(), lastError: null }).where(eq(schema.jobs.id, job.id));
        } catch (e) {
          const msg = e instanceof Error ? e.message : String(e);
          const dead = job.attempts >= job.maxAttempts;
          const backoff = Math.min(2 ** job.attempts * 30000, 6 * 3600000);
          await db.update(schema.jobs).set({
            status: dead ? "dead" : "queued", lockedAt: null, lastError: msg.slice(0, 2000), updatedAt: new Date(),
            runAt: new Date(Date.now() + backoff),
          }).where(eq(schema.jobs.id, job.id));
          console.error(`[job] ${job.type} failed (attempt ${job.attempts})`, msg);
        }
        done++;
      }
    }
    return done;
  })().finally(() => {
    draining = null;
  });
  return draining;
}

/** Replay a dead-lettered job (NFR-008). */
export async function replayJob(db: DB, id: string) {
  await db.update(schema.jobs).set({ status: "queued", attempts: 0, runAt: new Date(), lastError: null }).where(eq(schema.jobs.id, id));
}
