CREATE TABLE IF NOT EXISTS "backfills" (
  "id" text PRIMARY KEY NOT NULL,
  "pipeline" text NOT NULL,
  "status" text NOT NULL DEFAULT 'pending',
  "parent_id" text,
  "shard_index" integer,
  "shard_start_offset" bigint,
  "shard_end_offset" bigint,
  "read_source" text,
  "targets" text,
  "total_rows" bigint DEFAULT 0 NOT NULL,
  "rows_processed" bigint DEFAULT 0 NOT NULL,
  "rows_remaining" bigint,
  "batch_size" integer,
  "batch_number" integer DEFAULT 0 NOT NULL,
  "estimated_batches" integer,
  "percent_complete" real,
  "elapsed_seconds" real,
  "eta_seconds" real,
  "resume_cursor" jsonb,
  "scope_created_after" timestamp with time zone,
  "scope_created_before" timestamp with time zone,
  "scope_reason" text,
  "ch_analytics_inserted" bigint DEFAULT 0 NOT NULL,
  "ch_components_inserted" bigint DEFAULT 0 NOT NULL,
  "pg_analytics_inserted" bigint DEFAULT 0 NOT NULL,
  "pg_components_inserted" bigint DEFAULT 0 NOT NULL,
  "skipped" integer DEFAULT 0 NOT NULL,
  "errors" jsonb DEFAULT '[]'::jsonb NOT NULL,
  "last_error" text,
  "last_failed_at" timestamp with time zone,
  "project_id" text,
  "application_id" text,
  "dry_run" boolean DEFAULT false NOT NULL,
  "options" jsonb,
  "started_at" timestamp with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL,
  "updated_at" timestamp with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL,
  "completed_at" timestamp with time zone
);

CREATE INDEX IF NOT EXISTS "backfills_pipeline_status_idx"
  ON "backfills" ("pipeline", "status");

CREATE INDEX IF NOT EXISTS "backfills_parent_id_idx"
  ON "backfills" ("parent_id");

CREATE INDEX IF NOT EXISTS "backfills_updated_at_idx"
  ON "backfills" ("updated_at" DESC);
