ALTER TABLE gateway_task_admissions
  ADD COLUMN IF NOT EXISTS dispatch_next_at timestamptz NOT NULL DEFAULT now(),
  ADD COLUMN IF NOT EXISTS dispatch_failure_count integer NOT NULL DEFAULT 0,
  ADD COLUMN IF NOT EXISTS dispatch_last_outcome text,
  ADD COLUMN IF NOT EXISTS dispatch_last_error_code text,
  ADD COLUMN IF NOT EXISTS dispatch_last_error_at timestamptz;

ALTER TABLE gateway_task_admissions
  ADD CONSTRAINT gateway_task_admissions_dispatch_failure_count_check
  CHECK (dispatch_failure_count >= 0) NOT VALID;

ALTER TABLE gateway_task_admissions
  VALIDATE CONSTRAINT gateway_task_admissions_dispatch_failure_count_check;

CREATE INDEX IF NOT EXISTS idx_task_admissions_async_dispatch_due
  ON gateway_task_admissions(dispatch_next_at, priority, enqueued_at, task_id)
  WHERE status = 'waiting' AND mode = 'async';
