-- ================================================
-- Entrainment EN26 Program Workflow Configuration Insert Script
-- Program: EN26 - Entrainment 2026
-- Date: April 1-7, 2026
-- Registration Level: program
-- 3-Stage Flow: Registration -> Payment -> Travel
-- ================================================

-- Insert workflow configuration for Entrainment EN26
INSERT INTO workflow_configuration (
  workflow_key,
  workflow_name,
  program_type_key,
  program_type_id,
  workflow_version,
  lifecycle_status,
  description,
  data_query_template,
  registration_rules,
  initial_stage,
  created_by,
  updated_by,
  created_at,
  updated_at
) VALUES (
  'WF_ENTRAINMENT_EN26_V6',
  'Entrainment EN26 Registration Workflow',
  'PT_ENTRAINMENT',
  (SELECT id FROM program_type_v1 WHERE key = 'PT_ENTRAINMENT'),
  '1.0.0',
  'ACTIVE',
  'Entrainment EN26 (April 2026) registration workflow with 4 stages: Basic Details, Payment, Travel, Goodies',
  NULL, -- Will be generated from workflow variables
  '{
    "criteria": [
      {"field": "basicDetailsFilled", "operator": "EQUALS", "value": "completed"},
      {"operator": "OR", "conditions": [
        {"field": "paymentStatus", "operator": "IN", "value": ["online_completed", "offline_completed", "completed"]},
        {"field": "isFreeSeat", "operator": "EQUALS", "value": true}
      ]},
      {"field": "travelInfoStatus", "operator": "EQUALS", "value": "completed"},
      {"field": "travelPlanStatus", "operator": "EQUALS", "value": "completed"}
    ],
    "message": "Registration is completed when basic details, payment, and travel information are all submitted."
  }'::jsonb,
  NULL,
  -2,
  -2,
  '2026-02-23T00:00:00Z',
  '2026-02-23T00:00:00Z'
);

-- ================================================
-- Stage 1: REGISTRATION (Basic Details)
-- ================================================
INSERT INTO workflow_stage (
  workflow_config_id,
  stage_key,
  stage_name,
  stage_order,
  stage_category,
  is_optional,
  description,
  prerequisite_rules_config,
  execution_rules_config,
  action_buttons,
  completion_actions_config,
  created_by,
  updated_by,
  created_at,
  updated_at
) VALUES (
  (SELECT id FROM workflow_configuration WHERE workflow_key = 'WF_ENTRAINMENT_EN26_V6'),
  'REGISTRATION',
  'Basic Details',
  1,
  'FORM',
  false,
  'Seeker fills and submits basic registration details',
  '{
    "requiresAuth": true,
    "requiredStages": [],
    "conditions": [
      {"roles": ["ROLE_VIEWER", "ROLE_ADMIN", "ROLE_SHOBA", "ROLE_RELATIONAL_MANAGER"], "condition": {"field": "basicDetailsFilled", "operator": "NOT_EQUALS", "value": "completed"}, "message": "Login required to register"}
    ]
  }'::jsonb,
  '{
    "sections": [
      {
        "sectionKey": "FS_BASICDETAILS",
        "permissions": {
          "create": [{"roles": ["ROLE_VIEWER"], "condition": null}],
          "read": [{"roles": ["ALL"], "condition": null}],
          "update": [
            {"roles": ["ROLE_VIEWER"], "condition": {"operator": "AND", "conditions": [
              {"field": "basicDetailsFilled", "operator": "NOT_EQUALS", "value": "completed"},
              {"field": "registrationStatus", "operator": "NOT_IN", "value": ["waitlisted"]}
            ]}},
            {"roles": ["ROLE_ADMIN", "ROLE_SHOBA", "ROLE_RELATIONAL_MANAGER"], "condition": null}
          ],
          "delete": [{"roles": [], "condition": null}]
        }
      }
    ]
  }'::jsonb,
  '[
    {
      "actionKey": "CANCEL",
      "label": "Cancel",
      "type": "secondary",
      "icon": "close",
      "apiKey": null,
      "permissions": [{"roles": ["ROLE_ADMIN", "ROLE_SHOBA", "ROLE_RELATIONAL_MANAGER", "ROLE_VIEWER"], "condition": null}],
      "onSuccess": [{"roles": ["ROLE_ADMIN", "ROLE_SHOBA", "ROLE_RELATIONAL_MANAGER", "ROLE_VIEWER"], "showToast": false, "showSuccessScreen": false}]
    },
    {
      "actionKey": "SAVE_DRAFT",
      "label": "Save as Draft",
      "type": "secondary",
      "icon": "save",
      "apiKey": "SAVE_DRAFT",
      "permissions": [{"roles": ["ROLE_VIEWER"], "condition": {"operator": "AND", "conditions": [
        {"field": "allowsProxyRegistration", "operator": "EQUALS", "value": true},
        {"field": "basicDetailsFilled", "operator": "NOT_EQUALS", "value": "completed"}
      ]}}],
      "onSuccess": [{"roles": ["ROLE_VIEWER"], "showToast": true, "toast": {"message": "Draft saved successfully. You can continue later.", "type": "info"}, "showSuccessScreen": false}]
    },
    {
      "actionKey": "SUBMIT_REGISTRATION",
      "label": "Submit",
      "type": "primary",
      "icon": "send",
      "apiKey": "SUBMIT_REGISTRATION",
      "permissions": [{"roles": ["ROLE_VIEWER"], "condition": {"field": "basicDetailsFilled", "operator": "NOT_EQUALS", "value": "completed"}}],
      "onSuccess": [{
        "roles": ["ROLE_VIEWER"],
        "showToast": false,
        "showSuccessScreen": false
      }]
    }
  ]'::jsonb,
  '{"conditional": true, "conditions": [{"when": {"field": "basicDetailsFilled", "operator": "EQUALS", "value": "completed"}, "then": {"stageStatus": "completed", "markStageComplete": true}}]}'::jsonb,
  -2,
  -2,
  '2026-02-23T00:00:00Z',
  '2026-02-23T00:00:00Z'
);

-- ================================================
-- Stage 2: PAYMENT
-- ================================================
INSERT INTO workflow_stage (
  workflow_config_id,
  stage_key,
  stage_name,
  stage_order,
  stage_category,
  is_optional,
  description,
  prerequisite_rules_config,
  execution_rules_config,
  action_buttons,
  completion_actions_config,
  created_by,
  updated_by,
  created_at,
  updated_at
) VALUES (
  (SELECT id FROM workflow_configuration WHERE workflow_key = 'WF_ENTRAINMENT_EN26_V6'),
  'PAYMENT',
  'Payment',
  2,
  'FORM',
  false,
  'Process payment (online/offline) for Entrainment EN26',
  '{
    "requiresAuth": true,
    "requiredStages": ["REGISTRATION"],
    "conditions": [
      {"roles": ["ROLE_VIEWER"], "condition": {"operator": "AND", "conditions": [
        {"field": "requiresPayment", "operator": "EQUALS", "value": true},
        {"field": "isFreeSeat", "operator": "EQUALS", "value": false},
        {"field": "basicDetailsFilled", "operator": "EQUALS", "value": "completed"},
        {"operator": "OR", "conditions": [
          {"field": "registrationStatus", "operator": "NOT_IN", "value": ["waitlisted"]},
          {"field": "reservedLink", "operator": "EQUALS", "value": true}
        ]},
        {
          "operator": "OR",
          "conditions": [
            {"field": "paymentStatus", "operator": "IN", "value": ["online_pending", "failed"]},
            {"field": "paymentStatus", "operator": "IS_NULL"},
            {
              "operator": "AND",
              "conditions": [
                {"field": "paymentStatus", "operator": "EQUALS", "value": "offline_pending"},
                {"field": "editRequestStatus", "operator": "EQUALS", "value": "requested"}
              ]
            }
          ]
        }
      ]}, "message": "Basic details must be completed, not a free seat, seat must be available or admin-released, and payment must be pending or have an active edit request"},
      {"roles": ["ROLE_ADMIN", "ROLE_RELATIONAL_MANAGER"], "condition": {"operator": "AND", "conditions": [
        {"field": "requiresPayment", "operator": "EQUALS", "value": true},
        {"field": "isFreeSeat", "operator": "EQUALS", "value": false},
        {"field": "basicDetailsFilled", "operator": "EQUALS", "value": "completed"},
        {"operator": "OR", "conditions": [
          {"field": "registrationStatus", "operator": "NOT_IN", "value": ["waitlisted"]},
          {"field": "reservedLink", "operator": "EQUALS", "value": true}
        ]}
      ]}, "message": "Basic details must be completed, not a free seat, and seat must be available or admin-released"}
    ]
  }'::jsonb,
  '{
    "sections": [
      {
        "sectionKey": "FS_PAYMENTINVOICE",
        "permissions": {
          "create": [{"roles": ["ROLE_VIEWER"], "condition": {"operator": "AND", "conditions": [
            {"field": "requiresPayment", "operator": "EQUALS", "value": true},
            {"field": "isFreeSeat", "operator": "EQUALS", "value": false},
            {"field": "basicDetailsFilled", "operator": "EQUALS", "value": "completed"},
            {"operator": "OR", "conditions": [
              {"field": "registrationStatus", "operator": "NOT_IN", "value": ["waitlisted"]},
              {"field": "reservedLink", "operator": "EQUALS", "value": true}
            ]}
          ]}}],
          "read": [{"roles": ["ALL"], "condition": null}],
          "update": [
            {
              "roles": ["ROLE_VIEWER"],
              "condition": {
                "operator": "AND",
                "conditions": [
                  {"field": "requiresPayment", "operator": "EQUALS", "value": true},
                  {"field": "isFreeSeat", "operator": "EQUALS", "value": false},
                  {"field": "basicDetailsFilled", "operator": "EQUALS", "value": "completed"},
                  {"operator": "OR", "conditions": [
                    {"field": "registrationStatus", "operator": "NOT_IN", "value": ["waitlisted"]},
                    {"field": "reservedLink", "operator": "EQUALS", "value": true}
                  ]},
                  {
                    "operator": "OR",
                    "conditions": [
                      {"field": "paymentStatus", "operator": "IN", "value": ["online_pending", "failed"]},
                      {"field": "paymentStatus", "operator": "IS_NULL"},
                      {
                        "operator": "AND",
                        "conditions": [
                          {"field": "paymentStatus", "operator": "EQUALS", "value": "offline_pending"},
                          {"field": "editRequestStatus", "operator": "EQUALS", "value": "requested"}
                        ]
                      }
                    ]
                  }
                ]
              }
            },
            {"roles": ["ROLE_ADMIN", "ROLE_RELATIONAL_MANAGER"], "condition": null}
          ],
          "delete": [{"roles": [], "condition": null}]
        }
      }
    ]
  }'::jsonb,
  '[
    {
      "actionKey": "CANCEL",
      "label": "Cancel",
      "type": "secondary",
      "icon": "close",
      "apiKey": null,
      "permissions": [{"roles": ["ROLE_ADMIN", "ROLE_RELATIONAL_MANAGER", "ROLE_VIEWER"], "condition": null}],
      "onSuccess": [{"roles": ["ROLE_ADMIN", "ROLE_RELATIONAL_MANAGER", "ROLE_VIEWER"], "showToast": false, "showSuccessScreen": false}]
    },
    {
      "actionKey": "MAKE_PAYMENT",
      "label": "submit",
      "type": "primary",
      "icon": "payment",
      "apiKey": "MAKE_PAYMENT",
      "permissions": [{"roles": ["ROLE_VIEWER"], "condition": {"operator": "AND", "conditions": [
        {"field": "requiresPayment", "operator": "EQUALS", "value": true},
        {"field": "isFreeSeat", "operator": "EQUALS", "value": false},
        {"field": "basicDetailsFilled", "operator": "EQUALS", "value": "completed"},
        {"operator": "OR", "conditions": [
          {"field": "registrationStatus", "operator": "NOT_IN", "value": ["waitlisted"]},
          {"field": "reservedLink", "operator": "EQUALS", "value": true}
        ]},
        {
          "operator": "OR",
          "conditions": [
            {"field": "paymentStatus", "operator": "IN", "value": ["online_pending", "failed"]},
            {"field": "paymentStatus", "operator": "IS_NULL"},
            {
              "operator": "AND",
              "conditions": [
                {"field": "paymentStatus", "operator": "EQUALS", "value": "offline_pending"},
                {"field": "editRequestStatus", "operator": "EQUALS", "value": "requested"}
              ]
            }
          ]
        }
      ]}}],
      "onSuccess": [{
        "roles": ["ROLE_VIEWER"],
        "showToast": true,
        "toast": {"message": "Payment of {{programFee}} submitted successfully!", "type": "success"},
        "showSuccessScreen": true,
        "successScreen": {
          "title": "Payment Completed!",
          "message": "Your payment for {{programName}} ({{programStartDate}} to {{programEndDate}}) has been completed successfully. You can proceed with travel details.",
          "icon": "check_circle",
          "actions": [{"actionKey": "PROCEED_TO_TRAVEL", "label": "Proceed to Travel", "type": "primary", "icon": "flight", "apiKey": null, "condition": {"field": "involvesTravel", "operator": "EQUALS", "value": true}},
                      {"actionKey": "HOME", "label": "Go to Home", "type": "secondary", "icon": "home", "apiKey": null, "condition": null}]
        }
      }]
    }
  ]'::jsonb,
  '{"conditional": true, "conditions": [{"when": {"operator": "OR", "conditions": [
    {"field": "paymentStatus", "operator": "IN", "value": ["online_completed", "offline_completed", "completed"]},
    {"field": "isFreeSeat", "operator": "EQUALS", "value": true}
  ]}, "then": {"stageStatus": "completed", "markStageComplete": true}}]}'::jsonb,
  -2,
  -2,
  '2026-02-23T00:00:00Z',
  '2026-02-23T00:00:00Z'
);

-- ================================================
-- Stage 3: TRAVEL
-- ================================================
INSERT INTO workflow_stage (
  workflow_config_id,
  stage_key,
  stage_name,
  stage_order,
  stage_category,
  is_optional,
  description,
  prerequisite_rules_config,
  execution_rules_config,
  action_buttons,
  completion_actions_config,
  created_by,
  updated_by,
  created_at,
  updated_at
) VALUES (
  (SELECT id FROM workflow_configuration WHERE workflow_key = 'WF_ENTRAINMENT_EN26_V6'),
  'TRAVEL',
  'Travel',
  3,
  'FORM',
  false,
  'Submit travel information and plan for Entrainment EN26',
  '{
    "requiresAuth": true,
    "requiredStages": ["REGISTRATION", "PAYMENT"],
    "conditions": [
      {"roles": ["ROLE_VIEWER", "ROLE_ADMIN", "ROLE_RELATIONAL_MANAGER"], "condition": {"operator": "AND", "conditions": [
        {"field": "involvesTravel", "operator": "EQUALS", "value": true},
        {"operator": "OR", "conditions": [
          {"field": "paymentStatus", "operator": "IN", "value": ["online_completed", "offline_completed", "offline_pending", "completed"]},
          {"field": "isFreeSeat", "operator": "EQUALS", "value": true}
        ]},
        {"operator": "OR", "conditions": [
          {"field": "registrationStatus", "operator": "NOT_IN", "value": ["waitlisted"]},
          {"field": "reservedLink", "operator": "EQUALS", "value": true}
        ]}
      ]}, "message": "Payment must be completed or seat must be free, and not waitlisted (or admin-released)"}
    ]
  }'::jsonb,
  '{
    "sections": [
      {
        "sectionKey": "FS_TRAVELPLAN",
        "permissions": {
          "create": [{"roles": ["ROLE_VIEWER"], "condition": {"operator": "AND", "conditions": [
            {"field": "involvesTravel", "operator": "EQUALS", "value": true},
            {"operator": "OR", "conditions": [
              {"field": "paymentStatus", "operator": "IN", "value": ["online_completed", "offline_completed", "offline_pending", "completed"]},
              {"field": "isFreeSeat", "operator": "EQUALS", "value": true}
            ]},
            {"operator": "OR", "conditions": [
              {"field": "registrationStatus", "operator": "NOT_IN", "value": ["waitlisted"]},
              {"field": "reservedLink", "operator": "EQUALS", "value": true}
            ]}
          ]}}],
          "read": [{"roles": ["ALL"], "condition": null}],
          "update": [
            {"roles": ["ROLE_VIEWER"], "condition": {"field": "travelPlanStatus", "operator": "NOT_EQUALS", "value": "completed"}},
            {"roles": ["ROLE_ADMIN", "ROLE_RELATIONAL_MANAGER"], "condition": null}
          ],
          "delete": [{"roles": [], "condition": null}]
        }
      }
    ]
  }'::jsonb,
  '[
    {
      "actionKey": "CANCEL",
      "label": "Cancel",
      "type": "secondary",
      "icon": "close",
      "apiKey": null,
      "permissions": [{"roles": ["ROLE_ADMIN", "ROLE_RELATIONAL_MANAGER", "ROLE_VIEWER"], "condition": null}],
      "onSuccess": [{"roles": ["ROLE_ADMIN", "ROLE_RELATIONAL_MANAGER", "ROLE_VIEWER"], "showToast": false, "showSuccessScreen": false}]
    },
    {
      "actionKey": "SAVE_TRAVEL",
      "label": "submit",
      "type": "primary",
      "icon": "send",
      "apiKey": "SAVE_TRAVEL",
      "permissions": [{"roles": ["ROLE_VIEWER"], "condition": {"operator": "AND", "conditions": [
        {"field": "involvesTravel", "operator": "EQUALS", "value": true},
        {"operator": "OR", "conditions": [
          {"field": "paymentStatus", "operator": "IN", "value": ["online_completed", "offline_completed", "offline_pending", "completed"]},
          {"field": "isFreeSeat", "operator": "EQUALS", "value": true}
        ]},
        {"operator": "OR", "conditions": [
          {"field": "registrationStatus", "operator": "NOT_IN", "value": ["waitlisted"]},
          {"field": "reservedLink", "operator": "EQUALS", "value": true}
        ]}
      ]}}],
      "onSuccess": [{
        "roles": ["ROLE_VIEWER"],
        "showToast": true,
        "toast": {"message": "Travel details submitted successfully!", "type": "success"},
        "showSuccessScreen": true,
        "successScreen": {
          "title": "Registration Complete!",
          "message": "Your registration for {{programName}} is now complete. We look forward to seeing you at {{programVenue}} from {{programStartDate}} to {{programEndDate}}!",
          "icon": "check_circle",
          "actions": [
            {"actionKey": "PROCEED_TO_GOODIES", "label": "Go to Goodies", "type": "primary", "icon": "redeem", "apiKey": null, "condition": {"field": "hasGoodies", "operator": "EQUALS", "value": true}},
            {"actionKey": "HOME", "label": "Go to Home", "type": "secondary", "icon": "home", "apiKey": null, "condition": null}
          ]
        }
      }]
    }
  ]'::jsonb,
  '{"conditional": true, "conditions": [{"when": {"operator": "AND", "conditions": [
    {"field": "travelInfoStatus", "operator": "EQUALS", "value": "completed"},
    {"field": "travelPlanStatus", "operator": "EQUALS", "value": "completed"}
  ]}, "then": {"stageStatus": "completed", "markStageComplete": true}}]}'::jsonb,
  -2,
  -2,
  '2026-02-23T00:00:00Z',
  '2026-02-23T00:00:00Z'
);

-- ================================================
-- Stage 4: GOODIES (Optional)
-- ================================================
INSERT INTO workflow_stage (
  workflow_config_id,
  stage_key,
  stage_name,
  stage_order,
  stage_category,
  is_optional,
  description,
  prerequisite_rules_config,
  execution_rules_config,
  action_buttons,
  completion_actions_config,
  created_by,
  updated_by,
  created_at,
  updated_at
) VALUES (
  (SELECT id FROM workflow_configuration WHERE workflow_key = 'WF_ENTRAINMENT_EN26_V6'),
  'GOODIES',
  'Goodies',
  4,
  'FORM',
  true,
  'Select goodies/merchandise for Entrainment EN26',
  '{
    "requiresAuth": true,
    "requiredStages": ["REGISTRATION", "PAYMENT"],
    "conditions": [
      {"roles": ["ROLE_VIEWER", "ROLE_ADMIN", "ROLE_RELATIONAL_MANAGER"], "condition": {"operator": "AND", "conditions": [
        {"field": "hasGoodies", "operator": "EQUALS", "value": true},
        {"operator": "OR", "conditions": [
          {"field": "paymentStatus", "operator": "IN", "value": ["online_completed", "offline_completed", "offline_pending", "completed"]},
          {"field": "isFreeSeat", "operator": "EQUALS", "value": true}
        ]},
        {"operator": "OR", "conditions": [
          {"field": "registrationStatus", "operator": "NOT_IN", "value": ["waitlisted"]},
          {"field": "reservedLink", "operator": "EQUALS", "value": true}
        ]}
      ]}, "message": "Payment must be completed to access goodies selection, and not waitlisted (or admin-released)"}
    ]
  }'::jsonb,
  '{
    "sections": [
      {
        "sectionKey": "FS_GOODIES",
        "permissions": {
          "create": [{"roles": ["ROLE_VIEWER"], "condition": {"operator": "AND", "conditions": [
            {"field": "hasGoodies", "operator": "EQUALS", "value": true},
            {"operator": "OR", "conditions": [
              {"field": "paymentStatus", "operator": "IN", "value": ["online_completed", "offline_completed", "offline_pending", "completed"]},
              {"field": "isFreeSeat", "operator": "EQUALS", "value": true}
            ]}
          ]}}],
          "read": [{"roles": ["ALL"], "condition": null}],
          "update": [
            {"roles": ["ROLE_VIEWER"], "condition": {"field": "goodiesStatus", "operator": "NOT_EQUALS", "value": "completed"}},
            {"roles": ["ROLE_ADMIN", "ROLE_RELATIONAL_MANAGER"], "condition": null}
          ],
          "delete": [{"roles": [], "condition": null}]
        }
      }
    ]
  }'::jsonb,
  '[
    {
      "actionKey": "SKIP",
      "label": "Skip",
      "type": "secondary",
      "icon": "skip_next",
      "apiKey": null,
      "permissions": [{"roles": ["ROLE_VIEWER"], "condition": null}],
      "onSuccess": [{"roles": ["ROLE_VIEWER"], "showToast": false, "showSuccessScreen": false}]
    },
    {
      "actionKey": "SAVE_GOODIES",
      "label": "submit",
      "type": "primary",
      "icon": "send",
      "apiKey": "SAVE_GOODIES",
      "permissions": [{"roles": ["ROLE_VIEWER"], "condition": {"operator": "AND", "conditions": [
        {"field": "hasGoodies", "operator": "EQUALS", "value": true},
        {"operator": "OR", "conditions": [
          {"field": "paymentStatus", "operator": "IN", "value": ["online_completed", "offline_completed", "offline_pending", "completed"]},
          {"field": "isFreeSeat", "operator": "EQUALS", "value": true}
        ]}
      ]}}],
      "onSuccess": [{
        "roles": ["ROLE_VIEWER"],
        "showToast": true,
        "toast": {"message": "Goodies selection saved successfully!", "type": "success"},
        "showSuccessScreen": false
      }]
    }
  ]'::jsonb,
  '{"conditional": true, "conditions": [{"when": {"field": "goodiesStatus", "operator": "EQUALS", "value": "completed"}, "then": {"stageStatus": "completed", "markStageComplete": true}}]}'::jsonb,
  -2,
  -2,
  '2026-02-23T00:00:00Z',
  '2026-02-23T00:00:00Z'
);

-- ================================================
-- Ensure RESERVED_LINK variable exists in master catalog
-- ================================================
INSERT INTO workflow_variable_master (
  variable_key,
  variable_name,
  source_table,
  source_column,
  alias_name,
  data_type,
  join_type,
  join_condition,
  table_alias,
  description,
  is_active,
  is_mandatory_join,
  execution_order,
  variable_scope,
  created_by,
  updated_by,
  created_at,
  updated_at
) VALUES (
  'RESERVED_LINK',
  'Reserved Link',
  'hdb_program_registration',
  'reserved_link',
  'reservedLink',
  'boolean',
  NULL,
  NULL,
  NULL,
  'Whether an admin has released this waitlisted registration, allowing it to proceed to payment.',
  true,
  false,
  16,
  'DEFAULT',
  -2, -2, NOW(), NOW()
)
ON CONFLICT (variable_key) DO NOTHING;

-- ================================================
-- Link Variables to Entrainment EN26 Workflow
-- ================================================
DO $$
DECLARE
    v_workflow_id INT;
    v_var_id INT;
    v_order INT := 1;
BEGIN
    -- Get Entrainment EN26 workflow ID
    SELECT id INTO v_workflow_id FROM workflow_configuration WHERE workflow_key = 'WF_ENTRAINMENT_EN26_V6' LIMIT 1;
    
    IF v_workflow_id IS NOT NULL THEN
        -- Link all relevant variables for Entrainment workflow
        FOR v_var_id IN 
            SELECT id FROM workflow_variable_master 
            WHERE variable_key IN (
              'REGISTRATION_ID',
              'USER_ID',
              'PROGRAM_ID',
              'REGISTRATION_STATUS',
              'BASIC_DETAILS_STATUS',
              'PAYMENT_STATUS',
              'PAYMENT_MODE',
              'EDIT_REQUEST_STATUS',
              'TRAVEL_INFO_STATUS',
              'TRAVEL_PLAN_STATUS',
              'GOODIES_STATUS',
              'PRO_FORMA_INVOICE_PDF_URL',
              'IS_FREE_SEAT_COMPUTED',
              'IS_WAITLISTED',
              'RESERVED_LINK',
              'WAITLIST_POSITION',
              'INVOICE_GENERATED',
              'INVOICE_PDF_URL',
              'INVOICE_STATUS',
              'REGISTRATION_NUMBER',
              'SEEKER_NAME',
              'SEEKER_EMAIL',
              'SEEKER_PHONE',
              'PROGRAM_FEE',
              'PROGRAM_NAME',
              'PROGRAM_START_DATE',
              'PROGRAM_END_DATE',
              'PROGRAM_VENUE',
              -- Program flag variables (used in stage/button conditions)
              'APPROVAL_STATUS',
              'PROGRAM_REQUIRES_PAYMENT',
              'PROGRAM_INVOLVES_TRAVEL',
              'PROGRAM_HAS_GOODIES',
              'PROGRAM_REQUIRES_APPROVAL',
              'PROGRAM_ALLOWS_PROXY_REGISTRATION',
              'PROGRAM_HAS_TERMS'
            )
            ORDER BY execution_order, variable_key
        LOOP
            INSERT INTO workflow_configuration_variable 
            (workflow_config_id, variable_master_id, variable_order, is_required, created_by, updated_by)
            VALUES (v_workflow_id, v_var_id, v_order, false, -2, -2)
            ON CONFLICT DO NOTHING;
            v_order := v_order + 1;
        END LOOP;
        
        RAISE NOTICE 'Successfully linked % variables to Entrainment EN26 workflow (ID: %)', v_order - 1, v_workflow_id;
    ELSE
        RAISE NOTICE 'Entrainment EN26 workflow not found, skipping variable linking';
    END IF;
END $$;

-- ================================================
-- Verification Query
-- ================================================
-- SELECT 
--   wc.id, 
--   wc.workflow_key, 
--   wc.workflow_name, 
--   wc.lifecycle_status,
--   COUNT(ws.id) as stage_count,
--   COUNT(wcv.id) as variable_count
-- FROM workflow_configuration wc
-- LEFT JOIN workflow_stage ws ON ws.workflow_config_id = wc.id
-- LEFT JOIN workflow_configuration_variable wcv ON wcv.workflow_config_id = wc.id
-- WHERE wc.workflow_key = 'WF_ENTRAINMENT_EN26_V6'
-- GROUP BY wc.id, wc.workflow_key, wc.workflow_name, wc.lifecycle_status;



update program_v1
set workflow_id = (select id from workflow_configuration where workflow_key = 'WF_ENTRAINMENT_EN26_V6')
where program_type_id = (SELECT id FROM program_type_v1 WHERE key = 'PT_ENTRAINMENT');