ALTER TABLE IF EXISTS gateway_tasks
  ADD COLUMN IF NOT EXISTS river_job_id bigint,
  ADD COLUMN IF NOT EXISTS remote_task_id text,
  ADD COLUMN IF NOT EXISTS remote_task_payload jsonb;

UPDATE gateway_tasks
SET remote_task_payload = '{}'::jsonb
WHERE remote_task_payload IS NULL;

ALTER TABLE IF EXISTS gateway_tasks
  ALTER COLUMN remote_task_payload SET DEFAULT '{}'::jsonb;

CREATE INDEX IF NOT EXISTS idx_gateway_tasks_river_job
  ON gateway_tasks(river_job_id)
  WHERE river_job_id IS NOT NULL;

CREATE INDEX IF NOT EXISTS idx_gateway_tasks_async_recover
  ON gateway_tasks(async_mode, status, priority, created_at)
  WHERE async_mode = true AND status IN ('queued', 'running');
