-- ================================================
-- Entrainment Program Workflow Configuration Insert Script (V2)
-- Matches src/common/config/entrainment-workflow.ts (v2.0.0, 2026-02-19)
-- 3-Stage Flow: Registration -> Payment -> Travel
-- No edit after submission, admin-only updates
-- ================================================

-- Insert workflow configuration
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_V5',
  'Entrainment Program Registration Workflow',
  'PT_ENTRAINMENT',
  (SELECT id FROM program_type_v1 WHERE key = 'PT_ENTRAINMENT'),
  '3.0.0',
  'ACTIVE',
  'Entrainment program registration workflow with 3 stages (Basic Details, Payment, Travel) - No edit after submission',
  NULL, -- Will be generated from workflow variables
  '{
    "criteria": [
      {"field": "basicDetailsFilled", "operator": "EQUALS", "value": "completed"},
      {"field": "paymentStatus", "operator": "IN", "value": ["online_completed", "offline_completed", "completed"]},
      {"field": "travelInfoStatus", "operator": "EQUALS", "value": "completed"},
      {"field": "travelPlanStatus", "operator": "EQUALS", "value": "completed"}
    ],
    "message": "Registration is completed when all criteria are fulfilled."
  }'::jsonb,
  '{
    "stageKey": "REGISTRATION",
    "stageName": "Basic Details",
    "isOptional": true,
    "description": "Save progress and resume later"
  }'::jsonb,
  -2,
  -2,
  '2026-02-19T00:00:00Z',
  '2026-02-19T00: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_V5'),
  '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": null, "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": "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": true,
        "toast": {"message": "Registration submitted successfully!", "type": "success"},
        "showSuccessScreen": true,
        "successScreen": {
          "title": "Registration Submitted!",
          "message": "Your registration has been submitted successfully. Please proceed with payment if you are not waitlisted.",
          "icon": "check_circle",
          "actions": [{"actionKey": "HOME", "label": "Go to Home", "type": "primary", "icon": "home", "apiKey": null, "condition": null}]
        }
      }]
    }
  ]'::jsonb,
  '{"conditional": true, "conditions": [{"when": {"field": "basicDetailsFilled", "operator": "EQUALS", "value": "completed"}, "then": {"stageStatus": "completed", "markStageComplete": true}}]}'::jsonb,
  -2,
  -2,
  '2026-02-19T00:00:00Z',
  '2026-02-19T00: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_V5'),
  'PAYMENT',
  'Payment',
  2,
  'FORM',
  false,
  'Process payment (online/offline)',
  '{
    "requiresAuth": true,
    "requiredStages": ["BASICDETAILS"],
    "conditions": [
      {"roles": ["ROLE_VIEWER", "ROLE_ADMIN", "ROLE_RELATIONAL_MANAGER"], "condition": {"operator": "AND", "conditions": [
        {"field": "basicDetailsFilled", "operator": "EQUALS", "value": "completed"},
        {"field": "isWaitlisted", "operator": "EQUALS", "value": false},
        {"field": "registrationStatus", "operator": "NOT_IN", "value": ["waitlisted"]}
      ]}, "message": "Basic details must be completed and not waitlisted"}
    ]
  }'::jsonb,
  '{
    "sections": [
      {
        "sectionKey": "FS_PAYMENTINVOICE",
        "permissions": {
          "create": [{"roles": ["ROLE_VIEWER"], "condition": {"operator": "AND", "conditions": [
            {"field": "basicDetailsFilled", "operator": "EQUALS", "value": "completed"},
            {"field": "isWaitlisted", "operator": "EQUALS", "value": false},
            {"field": "registrationStatus", "operator": "NOT_IN", "value": ["waitlisted"]}
          ]}}],
          "read": [{"roles": ["ALL"], "condition": null}],
          "update": [{"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": "SUBMIT_PAYMENT",
      "label": "submit",
      "type": "primary",
      "icon": "payment",
      "apiKey": "SUBMIT_PAYMENT",
      "permissions": [{"roles": ["ROLE_VIEWER"], "condition": {"operator": "AND", "conditions": [
        {"field": "basicDetailsFilled", "operator": "EQUALS", "value": "completed"},
        {"field": "isWaitlisted", "operator": "EQUALS", "value": false},
        {"field": "registrationStatus", "operator": "NOT_IN", "value": ["waitlisted"]}
      ]}}],
      "onSuccess": [{
        "roles": ["ROLE_VIEWER"],
        "showToast": true,
        "toast": {"message": "Payment submitted successfully!", "type": "success"},
        "showSuccessScreen": true,
        "successScreen": {
          "title": "Payment Completed!",
          "message": "Your payment has been completed successfully. You can proceed with travel details once approved.",
          "icon": "check_circle",
          "actions": [{"actionKey": "HOME", "label": "home", "type": "secondary", "icon": "home", "apiKey": null, "condition": null}]
        }
      }]
    }
  ]'::jsonb,
  '{"conditional": true, "conditions": [{"when": {"field": "paymentStatus", "operator": "IN", "value": ["online_completed", "offline_completed", "completed"]}, "then": {"stageStatus": "completed", "markStageComplete": true}}]}'::jsonb,
  -2,
  -2,
  '2026-02-19T00:00:00Z',
  '2026-02-19T00: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_V5'),
  'TRAVEL',
  'Travel',
  3,
  'FORM',
  false,
  'Submit travel information and plan',
  '{
    "requiresAuth": true,
    "requiredStages": ["BASICDETAILS", "PAYMENT"],
    "conditions": [
      {"roles": ["ROLE_VIEWER", "ROLE_ADMIN", "ROLE_RELATIONAL_MANAGER"], "condition": {"operator": "AND", "conditions": [
        {"field": "paymentStatus", "operator": "IN", "value": ["online_completed", "offline_completed", "completed"]},
        {"field": "isWaitlisted", "operator": "EQUALS", "value": false},
        {"field": "registrationStatus", "operator": "NOT_IN", "value": ["waitlisted"]},
        {"field": "approvalStatus", "operator": "EQUALS", "value": "approved"}
      ]}, "message": "Payment must be completed, not waitlisted, and approval status must be approved"}
    ]
  }'::jsonb,
  '{
    "sections": [
      {
        "sectionKey": "FS_TRAVELPLAN",
        "permissions": {
          "create": [{"roles": ["ROLE_VIEWER"], "condition": {"operator": "AND", "conditions": [
            {"field": "paymentStatus", "operator": "IN", "value": ["online_completed", "offline_completed", "completed"]},
            {"field": "isWaitlisted", "operator": "EQUALS", "value": false},
            {"field": "approvalStatus", "operator": "EQUALS", "value": "approved"},
            {"field": "registrationStatus", "operator": "NOT_IN", "value": ["waitlisted"]}
          ]}}],
          "read": [{"roles": ["ALL"], "condition": null}],
          "update": [{"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": "SUBMIT_TRAVEL",
      "label": "submit",
      "type": "primary",
      "icon": "send",
      "apiKey": "SUBMIT_TRAVEL",
      "permissions": [{"roles": ["ROLE_VIEWER"], "condition": {"operator": "AND", "conditions": [
        {"field": "paymentStatus", "operator": "IN", "value": ["online_completed", "offline_completed", "completed"]},
        {"field": "isWaitlisted", "operator": "EQUALS", "value": false},
        {"field": "registrationStatus", "operator": "NOT_IN", "value": ["waitlisted"]},
        {"field": "approvalStatus", "operator": "EQUALS", "value": "approved"}
      ]}}],
      "onSuccess": [{
        "roles": ["ROLE_VIEWER"],
        "showToast": true,
        "toast": {"message": "Travel details submitted successfully!", "type": "success"},
        "showSuccessScreen": true,
        "successScreen": {
          "title": "Registration Complete!",
          "message": "Your registration for the Entrainment Program is now complete. We look forward to seeing you!",
          "icon": "check_circle",
          "actions": [{"actionKey": "HOME", "label": "home", "type": "primary", "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-19T00:00:00Z',
  '2026-02-19T00:00:00Z'
);

-- ================================================
-- Link Variables to Entrainment Workflow
-- ================================================
DO $$
DECLARE
    v_workflow_id INT;
    v_var_id INT;
    v_order INT := 1;
BEGIN
    -- Get Entrainment workflow ID
    SELECT id INTO v_workflow_id FROM workflow_configuration WHERE workflow_key = 'WF_ENTRAINMENT_V5' 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',
                'APPROVAL_STATUS',
                'PAYMENT_STATUS',
                'PAYMENT_MODE',
                'TRAVEL_INFO_STATUS',
                'TRAVEL_PLAN_STATUS',
                'PRO_FORMA_INVOICE_PDF_URL',
                'IS_FREE_SEAT_COMPUTED',
                'IS_WAITLISTED',
                'WAITLIST_POSITION',
                'INVOICE_GENERATED',
                'INVOICE_PDF_URL',
                'INVOICE_STATUS',
                'REGISTRATION_NUMBER',
                'SEEKER_NAME',
                'SEEKER_EMAIL',
                'SEEKER_PHONE'
            )
            ORDER BY execution_order, variable_key
        LOOP
            INSERT INTO workflow_configuration_variable 
            (workflow_config_id, variable_master_id, variable_order, is_required)
            VALUES (v_workflow_id, v_var_id, v_order, false)
            ON CONFLICT DO NOTHING;
            v_order := v_order + 1;
        END LOOP;
        
        RAISE NOTICE 'Linked % variables to Entrainment workflow (ID: %)', v_order - 1, v_workflow_id;
    ELSE
        RAISE NOTICE 'Entrainment workflow not found, skipping variable linking';
    END IF;
END $$;
