CREATE TABLE IF NOT EXISTS rollouts (
  id VARCHAR(255) PRIMARY KEY UNIQUE NOT NULL,
  namespace_key VARCHAR(255) NOT NULL REFERENCES namespaces ON DELETE CASCADE,
  flag_key VARCHAR(255) NOT NULL,
  type INTEGER DEFAULT 0 NOT NULL,
  description TEXT NOT NULL,
  rank INTEGER DEFAULT 1 NOT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
  FOREIGN KEY (namespace_key, flag_key) REFERENCES flags (namespace_key, key) ON DELETE CASCADE
);

CREATE TABLE IF NOT EXISTS rollout_thresholds (
  id VARCHAR(255) PRIMARY KEY UNIQUE NOT NULL,
  namespace_key VARCHAR(255) NOT NULL REFERENCES namespaces ON DELETE CASCADE,
  rollout_id VARCHAR(255) UNIQUE NOT NULL REFERENCES rollouts ON DELETE CASCADE,
  percentage float DEFAULT 0 NOT NULL,
  value BOOLEAN DEFAULT FALSE NOT NULL
);

CREATE TABLE IF NOT EXISTS rollout_segments (
  id VARCHAR(255) PRIMARY KEY UNIQUE NOT NULL,
  namespace_key VARCHAR(255) NOT NULL,
  rollout_id VARCHAR(255) NOT NULL REFERENCES rollouts ON DELETE CASCADE,
  segment_key VARCHAR(255) NOT NULL,
  value BOOLEAN DEFAULT FALSE NOT NULL,
  CONSTRAINT fk_namespace_key_ref_namespaces FOREIGN KEY (namespace_key) REFERENCES namespaces ON DELETE CASCADE,
  CONSTRAINT fk_namespace_key_ref_segments FOREIGN KEY (namespace_key, segment_key) REFERENCES segments (namespace_key, key) ON DELETE CASCADE
);
