create schema if not exists kbx;

-- Runtime overrides are operational controls; code contracts remain the canonical definition of safe experiment scope.
create table if not exists kbx.experiment_runtime (
  tenant_id uuid not null,
  experiment_id varchar(160) not null,
  state varchar(24) not null check(state in ('draft','running','paused','rolled-back','graduated','completed')),
  rollout_percent integer not null check(rollout_percent between 0 and 100),
  kill_switch boolean not null default false,
  version integer not null default 1,
  updated_by uuid,
  updated_at timestamptz not null default now(),
  primary key(tenant_id,experiment_id)
);

create table if not exists kbx.experiment_assignments (
  tenant_id uuid not null,
  experiment_id varchar(160) not null,
  user_id uuid not null,
  variant varchar(80) not null,
  assigned_at timestamptz not null default now(),
  primary key(tenant_id,experiment_id,user_id)
);
create index if not exists ix_experiment_assignments_experiment on kbx.experiment_assignments(tenant_id,experiment_id,variant);

create table if not exists kbx.experiment_audit (
  id uuid primary key,
  tenant_id uuid not null,
  experiment_id varchar(160) not null,
  action varchar(40) not null,
  before_state jsonb,
  after_state jsonb,
  actor_id uuid,
  reason varchar(500) not null,
  correlation_id varchar(100),
  occurred_at timestamptz not null default now()
);
create index if not exists ix_experiment_audit_time on kbx.experiment_audit(tenant_id,experiment_id,occurred_at desc);

-- Optional experiment context is low-cardinality metadata only; no business/customer identity is added.
alter table kbx.ux_events add column if not exists experiment_id varchar(160);
alter table kbx.ux_events add column if not exists experiment_variant varchar(80);
create index if not exists ix_ux_events_experiment_time on kbx.ux_events(tenant_id,experiment_id,experiment_variant,occurred_at desc) where experiment_id is not null;
