ALTER TABLE gateway_request_assets
  ADD COLUMN IF NOT EXISTS storage_channel_id uuid REFERENCES file_storage_channels(id) ON DELETE SET NULL,
  ADD COLUMN IF NOT EXISTS storage_channel_key text,
  ADD COLUMN IF NOT EXISTS object_key text,
  ADD COLUMN IF NOT EXISTS access_scope text DEFAULT 'private';

ALTER TABLE gateway_tasks
  ADD COLUMN IF NOT EXISTS public_error jsonb;

ALTER TABLE gateway_task_attempts
  ADD COLUMN IF NOT EXISTS public_error jsonb;

CREATE INDEX IF NOT EXISTS idx_gateway_request_assets_object
  ON gateway_request_assets(storage_channel_key, object_key)
  WHERE object_key IS NOT NULL;

UPDATE system_settings
SET value = jsonb_set(COALESCE(value, '{}'::jsonb), '{resultUploadPolicy}', '"default"'::jsonb, true),
    updated_at = now()
WHERE setting_key = 'file_storage'
  AND COALESCE(value->>'resultUploadPolicy', '') IN ('upload_none', 'none', 'never', 'disabled', 'no_upload', 'skip', 'skip_all');
