CREATE TABLE IF NOT EXISTS gateway_task_param_preprocessing_logs (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  task_id uuid NOT NULL REFERENCES gateway_tasks(id) ON DELETE CASCADE,
  attempt_id uuid REFERENCES gateway_task_attempts(id) ON DELETE SET NULL,
  attempt_no integer,
  model_type text NOT NULL DEFAULT '',
  platform_id uuid REFERENCES integration_platforms(id) ON DELETE SET NULL,
  platform_model_id uuid REFERENCES platform_models(id) ON DELETE SET NULL,
  client_id text,
  changed boolean NOT NULL DEFAULT false,
  change_count integer NOT NULL DEFAULT 0,
  actual_input jsonb NOT NULL DEFAULT '{}'::jsonb,
  converted_output jsonb NOT NULL DEFAULT '{}'::jsonb,
  changes jsonb NOT NULL DEFAULT '[]'::jsonb,
  model_snapshot jsonb NOT NULL DEFAULT '{}'::jsonb,
  created_at timestamptz NOT NULL DEFAULT now()
);

CREATE INDEX IF NOT EXISTS idx_gateway_task_param_pre_logs_task
  ON gateway_task_param_preprocessing_logs(task_id, created_at);

CREATE INDEX IF NOT EXISTS idx_gateway_task_param_pre_logs_attempt
  ON gateway_task_param_preprocessing_logs(attempt_id)
  WHERE attempt_id IS NOT NULL;

CREATE INDEX IF NOT EXISTS idx_gateway_task_param_pre_logs_changed
  ON gateway_task_param_preprocessing_logs(changed, created_at DESC);

CREATE INDEX IF NOT EXISTS idx_gateway_task_param_pre_logs_changes
  ON gateway_task_param_preprocessing_logs USING gin(changes);
