-- Migration 035: Update Veeam Backup Failure pipeline to use B2 storage for diagnostic results
-- Inserts a fetch_b2_result step after rmm_get_job_results and updates references

DO $$
DECLARE
  v_pipeline_id INTEGER;
BEGIN
  SELECT id INTO v_pipeline_id FROM webhook_pipelines WHERE name = 'Veeam Backup Failure → Smart Diagnostic Ticket';
  IF v_pipeline_id IS NULL THEN
    RAISE NOTICE 'Veeam pipeline not found — skipping';
    RETURN;
  END IF;

  -- Shift steps 10-13 → 11-14 to make room for the new fetch_b2_result step at position 10
  -- Update in reverse order to avoid unique constraint conflicts on (pipeline_id, step_order)
  UPDATE pipeline_steps SET step_order = 14 WHERE pipeline_id = v_pipeline_id AND step_order = 13;
  UPDATE pipeline_steps SET step_order = 13 WHERE pipeline_id = v_pipeline_id AND step_order = 12;
  UPDATE pipeline_steps SET step_order = 12 WHERE pipeline_id = v_pipeline_id AND step_order = 11;
  UPDATE pipeline_steps SET step_order = 11 WHERE pipeline_id = v_pipeline_id AND step_order = 10;

  -- Insert fetch_b2_result step at position 10
  INSERT INTO pipeline_steps (pipeline_id, step_order, step_type, name, config)
  VALUES (
    v_pipeline_id, 10, 'fetch_b2_result', 'Download diagnostic results from B2',
    '{
      "object_key": "{{context.job_results}}",
      "output_key": "diagnostic_results"
    }'::jsonb
  );

  -- Update AI analyze step (now step 11): replace {{context.job_results}} with {{context.diagnostic_results}}
  UPDATE pipeline_steps
    SET config = jsonb_set(
      config,
      '{prompt}',
      to_jsonb(replace(config->>'prompt', '{{context.job_results}}', '{{context.diagnostic_results}}'))
    )
    WHERE pipeline_id = v_pipeline_id AND step_type = 'ai_analyze';

  -- Update create_ticket step (now step 12): replace {{context.job_results}} with {{context.diagnostic_results}}
  UPDATE pipeline_steps
    SET config = jsonb_set(
      config,
      '{template,description}',
      to_jsonb(replace(config->'template'->>'description', '{{context.job_results}}', '{{context.diagnostic_results}}'))
    )
    WHERE pipeline_id = v_pipeline_id AND step_type = 'create_ticket';

  RAISE NOTICE 'Veeam pipeline updated: inserted fetch_b2_result at step 10, shifted steps 10-13 → 11-14, updated references';
END $$;
