SET NAMES utf8mb4;

CREATE TABLE IF NOT EXISTS ab_distribution_batches (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  workspace_id BIGINT UNSIGNED NOT NULL,
  experiment_id BIGINT UNSIGNED NOT NULL,
  campaign_id BIGINT UNSIGNED NOT NULL,
  distribution_mode ENUM('balanced','randomized') NOT NULL DEFAULT 'balanced',
  requested_quantity INT UNSIGNED NOT NULL,
  weights_json LONGTEXT NOT NULL,
  allocation_json LONGTEXT NOT NULL,
  created_by BIGINT UNSIGNED NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  INDEX idx_abdb_ws_time(workspace_id,created_at),
  INDEX idx_abdb_experiment(experiment_id),
  CONSTRAINT fk_abdb_workspace FOREIGN KEY(workspace_id) REFERENCES workspaces(id) ON DELETE CASCADE,
  CONSTRAINT fk_abdb_experiment FOREIGN KEY(experiment_id) REFERENCES ab_experiments(id) ON DELETE CASCADE,
  CONSTRAINT fk_abdb_campaign FOREIGN KEY(campaign_id) REFERENCES campaigns(id) ON DELETE CASCADE,
  CONSTRAINT fk_abdb_user FOREIGN KEY(created_by) REFERENCES users(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

ALTER TABLE ab_experiment_assignments
  ADD COLUMN distribution_batch_id BIGINT UNSIGNED NULL AFTER scheduled_post_id,
  ADD INDEX idx_aba_distribution_batch(distribution_batch_id),
  ADD CONSTRAINT fk_aba_distribution_batch FOREIGN KEY(distribution_batch_id) REFERENCES ab_distribution_batches(id) ON DELETE SET NULL;
