ALTER TABLE gateway_worker_instances
  DROP CONSTRAINT gateway_worker_instances_status_check,
  ADD COLUMN draining_at timestamptz,
  ADD CONSTRAINT gateway_worker_instances_status_check
    CHECK (status IN ('active', 'draining', 'stale'));

CREATE TABLE gateway_capacity_profiles (
  profile_key text PRIMARY KEY,
  release_sha text NOT NULL,
  config_hash text NOT NULL,
  acceptance_run_id uuid REFERENCES gateway_acceptance_runs(id) ON DELETE RESTRICT,
  kind text NOT NULL,
  model text NOT NULL DEFAULT '*',
  capacity_profile text NOT NULL,
  stable_throughput_per_second numeric(18, 6) NOT NULL,
  admitted_throughput_per_second numeric(18, 6) NOT NULL,
  max_running integer NOT NULL,
  max_queued integer NOT NULL,
  max_predicted_wait_seconds integer NOT NULL,
  enabled boolean NOT NULL DEFAULT false,
  metadata jsonb NOT NULL DEFAULT '{}'::jsonb,
  created_at timestamptz NOT NULL DEFAULT now(),
  updated_at timestamptz NOT NULL DEFAULT now(),
  CONSTRAINT gateway_capacity_profiles_kind_check
    CHECK (kind IN ('image', 'video', 'mixed')),
  CONSTRAINT gateway_capacity_profiles_values_check
    CHECK (
      stable_throughput_per_second > 0
      AND admitted_throughput_per_second > 0
      AND admitted_throughput_per_second <= stable_throughput_per_second
      AND max_running > 0
      AND max_queued >= 0
      AND max_predicted_wait_seconds > 0
    )
);

CREATE UNIQUE INDEX uniq_gateway_capacity_profiles_enabled_kind_model
  ON gateway_capacity_profiles (kind, model)
  WHERE enabled = true;
