-- ImageHub: labeling-pipeline stages on a dataset (Label -> Review_1 -> Review_2 ...). Each stage
-- has a kind (label/review), an order (seq), an optional review_percent (review stages only), and
-- an auto_assign flag (the "Automatic Task Assignment" toggle). Idempotent (CREATE ... IF NOT
-- EXISTS) so the startup runner can apply it to volumes that predate it. Apply after 019 (no
-- semicolons inside comments or string literals — the runner splitter is naive):
--   docker exec -i initiative-postgres psql -U initiative -d initiatives < be0/migrations/020_imagehub_dataset_stages.sql

CREATE TABLE IF NOT EXISTS imagehub_dataset_stages (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  dataset_id UUID NOT NULL REFERENCES imagehub_datasets(id) ON DELETE CASCADE,
  name TEXT NOT NULL,
  kind TEXT NOT NULL DEFAULT 'label' CHECK (kind IN ('label','review')),
  seq INTEGER NOT NULL DEFAULT 0,
  review_percent INTEGER CHECK (review_percent IS NULL OR (review_percent >= 0 AND review_percent <= 100)),
  auto_assign BOOLEAN NOT NULL DEFAULT TRUE,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- Stages of a dataset, in pipeline order.
CREATE INDEX IF NOT EXISTS idx_imagehub_dataset_stages_dataset
  ON imagehub_dataset_stages (dataset_id, seq);

-- A stage name is unique within its dataset.
CREATE UNIQUE INDEX IF NOT EXISTS uq_imagehub_dataset_stages_name
  ON imagehub_dataset_stages (dataset_id, name);
