CREATE TABLE gateway_acceptance_runs (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  status text NOT NULL DEFAULT 'pending'
    CHECK (status IN ('pending', 'running', 'passed', 'failed', 'promoted', 'aborted')),
  release_sha text NOT NULL,
  api_image_digest text NOT NULL,
  worker_image_digest text NOT NULL,
  api_key_id text NOT NULL,
  user_id text NOT NULL,
  token_sha256 text NOT NULL,
  emulator_base_url text NOT NULL,
  callback_url text,
  capacity_profile text NOT NULL DEFAULT 'P24'
    CHECK (capacity_profile IN ('P24', 'P28', 'P32')),
  config jsonb NOT NULL DEFAULT '{}'::jsonb,
  report jsonb NOT NULL DEFAULT '{}'::jsonb,
  failure_reason text,
  started_at timestamptz,
  finished_at timestamptz,
  promoted_at timestamptz,
  created_at timestamptz NOT NULL DEFAULT now(),
  updated_at timestamptz NOT NULL DEFAULT now()
);

CREATE INDEX idx_gateway_acceptance_runs_status_created
  ON gateway_acceptance_runs (status, created_at DESC);

ALTER TABLE gateway_tasks
  ADD COLUMN acceptance_run_id uuid REFERENCES gateway_acceptance_runs(id),
  ADD CONSTRAINT gateway_tasks_acceptance_run_mode_check CHECK (
    (
      run_mode IN ('acceptance', 'acceptance_canary')
      AND acceptance_run_id IS DISTINCT FROM NULL
    )
    OR (
      run_mode NOT IN ('acceptance', 'acceptance_canary')
      AND acceptance_run_id IS NULL
    )
  ) NOT VALID;

CREATE INDEX idx_gateway_tasks_acceptance_run
  ON gateway_tasks (acceptance_run_id, status, created_at)
  WHERE acceptance_run_id IS NOT NULL;

INSERT INTO system_settings (setting_key, value)
VALUES (
  'gateway_traffic_mode',
  '{"mode":"live","revision":0}'::jsonb
)
ON CONFLICT (setting_key) DO NOTHING;
