CREATE TABLE "background_jobs" (
    "id" TEXT NOT NULL,
    "type" TEXT NOT NULL,
    "status" TEXT NOT NULL DEFAULT 'queued',
    "dedupe_key" TEXT,
    "payload" JSONB NOT NULL DEFAULT '{}',
    "attempts" INTEGER NOT NULL DEFAULT 0,
    "max_attempts" INTEGER NOT NULL DEFAULT 3,
    "available_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "locked_by" TEXT,
    "locked_until" TIMESTAMP(3),
    "last_error" TEXT,
    "completed_at" TIMESTAMP(3),
    "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "background_jobs_pkey" PRIMARY KEY ("id")
);

CREATE INDEX "background_jobs_status_available_at_idx"
  ON "background_jobs"("status", "available_at" ASC, "created_at" ASC);

CREATE INDEX "background_jobs_type_status_available_at_idx"
  ON "background_jobs"("type", "status", "available_at" ASC);

CREATE INDEX "background_jobs_lease_idx"
  ON "background_jobs"("status", "locked_until" ASC)
  WHERE "locked_until" IS NOT NULL;

CREATE UNIQUE INDEX "background_jobs_active_dedupe_key_idx"
  ON "background_jobs"("type", "dedupe_key")
  WHERE "dedupe_key" IS NOT NULL AND "status" IN ('queued', 'running');
