-- ImageHub: dataset membership — lets users other than the owner work a dataset's tasks
-- (multi-labeler). MVP treats all members as labelers: they view the dataset and work tasks
-- assigned to them, while dataset / stage / settings management stays with the owner + platform
-- admins. The role column is reserved for a future project-admin tier. Idempotent. Apply after 022
-- (no semicolons inside comments or string literals — the runner splitter is naive):
--   docker exec -i initiative-postgres psql -U initiative -d initiatives < be0/migrations/023_imagehub_dataset_members.sql

CREATE TABLE IF NOT EXISTS imagehub_dataset_members (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  dataset_id UUID NOT NULL REFERENCES imagehub_datasets(id) ON DELETE CASCADE,
  user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  role TEXT NOT NULL DEFAULT 'member' CHECK (role IN ('project_admin','member')),
  added_by UUID REFERENCES users(id) ON DELETE SET NULL,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- One membership per user per dataset.
CREATE UNIQUE INDEX IF NOT EXISTS uq_imagehub_dataset_members_user
  ON imagehub_dataset_members (dataset_id, user_id);

-- "Datasets I am a member of" lookup (the member's dataset list).
CREATE INDEX IF NOT EXISTS idx_imagehub_dataset_members_user
  ON imagehub_dataset_members (user_id);
