-- ================================================
-- TAT TA26 Program Workflow Configuration Insert Script
-- Program: TA26 - TAT 2026
-- Date: May 1 - July 17, 2026 (12 weeks, 12 sessions)
-- Registration Level: program
-- Mode: Online (Webinar)
-- 2-Stage Flow: Registration -> Payment
-- ================================================

-- Insert workflow configuration for TAT TA26
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_TAT_TA26_V6',
  'TAT TA26 Registration Workflow',
  'PT_TAT',
  (SELECT id FROM program_type_v1 WHERE key = 'PT_TAT'),
  '1.0.0',
  'ACTIVE',
  'TAT TA26 (May-July 2026) online webinar registration workflow with 2 stages: Basic Details, Payment',
  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}
      ]}
    ],
    "message": "Registration is completed when basic details and payment are 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_TAT_TA26_V6'),
  'REGISTRATION',
  'Basic Details',
  1,
  'FORM',
  false,
  'Seeker fills and submits basic registration details for TAT TA26',
  '{
    "requiresAuth": true,
    "requiredStages": [],
    "conditions": [
      {"roles": ["ROLE_VIEWER"], "condition": {"operator": "AND", "conditions": [
        {"field": "basicDetailsFilled", "operator": "NOT_EQUALS", "value": "completed"},
        {"field": "registrationStatus", "operator": "NOT_IN", "value": ["waitlisted"]}
      ]}, "message": "Registration details already completed or you are on the waitlist"},
      {"roles": ["ROLE_ADMIN", "ROLE_SHOBA", "ROLE_RELATIONAL_MANAGER"], "condition": null, "message": null}
    ]
  }'::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": {"field": "basicDetailsFilled", "operator": "EQUALS", "value": "completed"}}
          ],
          "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": {"operator": "AND", "conditions": [
        {"field": "basicDetailsFilled", "operator": "NOT_EQUALS", "value": "completed"},
        {"field": "isWaitlisted", "operator": "EQUALS", "value": false},
        {"field": "registrationStatus", "operator": "NOT_IN", "value": ["waitlisted"]}
      ]}}],
      "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_TAT_TA26_V6'),
  'PAYMENT',
  'Payment',
  2,
  'FORM',
  false,
  'Process payment (online/offline) for TAT TA26',
  '{
    "requiresAuth": true,
    "requiredStages": ["REGISTRATION"],
    "conditions": [
      {"roles": ["ROLE_VIEWER"], "condition": {"operator": "AND", "conditions": [
        {"field": "requiresPayment", "operator": "EQUALS", "value": true},
        {"field": "basicDetailsFilled", "operator": "EQUALS", "value": "completed"},
        {"field": "registrationStatus", "operator": "NOT_IN", "value": ["rejected"]},
        {"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, registration must not be rejected or waitlisted, and payment must be pending or have an active edit request"},
      {"roles": ["ROLE_ADMIN", "ROLE_SHOBA", "ROLE_RELATIONAL_MANAGER"], "condition": null, "message": null}
    ]
  }'::jsonb,
  '{
    "sections": [
      {
        "sectionKey": "FS_PAYMENTINVOICE",
        "permissions": {
          "create": [{"roles": ["ROLE_VIEWER"], "condition": {"operator": "AND", "conditions": [
            {"field": "requiresPayment", "operator": "EQUALS", "value": true},
            {"field": "basicDetailsFilled", "operator": "EQUALS", "value": "completed"},
            {"field": "registrationStatus", "operator": "NOT_IN", "value": ["rejected"]},
            {"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": "basicDetailsFilled", "operator": "EQUALS", "value": "completed"},
                  {"field": "registrationStatus", "operator": "NOT_IN", "value": ["rejected"]},
                  {"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_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": "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": "basicDetailsFilled", "operator": "EQUALS", "value": "completed"},
        {"field": "registrationStatus", "operator": "NOT_IN", "value": ["rejected"]},
        {"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": false,
          "showSuccessScreen": true,
          "successScreenConfig": {
            "scenarios": [
              {
                "scenarioKey": "PAYMENT_EDIT_REQUESTED",
                "condition": {
                  "operator": "AND",
                  "conditions": [
                    {"field": "paymentMode", "operator": "EQUALS", "value": "offline"},
                    {"field": "paymentStatus", "operator": "EQUALS", "value": "offline_pending"},
                    {"field": "editRequestStatus", "operator": "EQUALS", "value": "requested"}
                  ]
                },
                "screen": {
                  "title": "{{programName}}",
                  "message": "Dear infinitheist {{seekerName}},\n\nYour payment edit request for {{programName}} has been submitted.\n\nYou can edit your payment details once the request is approved.",
                  "variant": "info",
                  "showLogo": true,
                  "showBanner": true,
                  "logoUrl": "{{logoUrl}}",
                  "bannerImageUrl": "{{bannerImageUrl}}",
                  "actions": [
                    {
                      "actionKey": "HOME",
                      "label": "home",
                      "type": "secondary",
                      "apiKey": null
                    },
                    {
                      "actionKey": "UPDATE_PAYMENT",
                      "label": "update payment",
                      "type": "secondary",
                      "apiKey": "UPDATE_PAYMENT_DETAILS"
                    }
                  ]
                }
              },
              {
                "scenarioKey": "ONLINE_PAYMENT_SUCCESS",
                "condition": {
                  "operator": "AND",
                  "conditions": [
                    {"field": "paymentMode", "operator": "EQUALS", "value": "online"},
                    {"field": "paymentStatus", "operator": "IN", "value": ["online_completed", "completed"]}
                  ]
                },
                "screen": {
                  "title": "Registration Confirmation",
                  "message": "Congratulations on your successful registration for {{programName}}, a life-transforming 12-session experience with Mahatria.\n\n\nYour registration number is: {{registrationNumber}}\n\n\nThe access details and recommended digital disciplines will be communicated to you a day before the commencement of the program.\n\n\nLet this ''TAT'' magnetise the best of everything in your life.",
                  "variant": "success",
                  "showLogo": true,
                  "showBanner": true,
                  "logoUrl": "{{logoUrl}}",
                  "bannerImageUrl": "{{bannerImageUrl}}",
                  "actions": [
                    {
                      "actionKey": "DOWNLOAD_INVOICE",
                      "label": "download invoice",
                      "type": "secondary",
                      "apiKey": "DOWNLOAD_INVOICE"
                    },
                    {
                      "actionKey": "HOME",
                      "label": "home",
                      "type": "secondary",
                      "apiKey": null
                    }
                  ]
                }
              },
              {
                "scenarioKey": "OFFLINE_PAYMENT_CHEQUE",
                "condition": {
                  "operator": "AND",
                  "conditions": [
                    {"field": "paymentMode", "operator": "EQUALS", "value": "offline"},
                    {"field": "offlinePaymentMethod", "operator": "EQUALS", "value": "Cheque"}
                  ]
                },
                "screen": {
                  "title": "Registration Acknowledgement",
                  "message": "We acknowledge your registration for {{programName}}, a life-transforming 12-session experience with Mahatria.\n\n\nYour provisional registration number is: {{registrationNumber}}\n\n\nThe access details and recommended digital disciplines will be communicated to you a day before the commencement of the program.\n\n\nNote: Payment is subject to realization. A confirmation email along with the invoice will follow upon payment realization.\n\n\nLet this ''TAT'' magnetise the best of everything in your life.",
                  "variant": "info",
                  "showLogo": true,
                  "showBanner": true,
                  "logoUrl": "{{logoUrl}}",
                  "bannerImageUrl": "{{bannerImageUrl}}",
                  "actions": [
                    {
                      "actionKey": "HOME",
                      "label": "home",
                      "type": "secondary",
                      "apiKey": null
                    }
                  ]
                }
              },
              {
                "scenarioKey": "OFFLINE_PAYMENT_OTHER",
                "condition": {
                  "operator": "AND",
                  "conditions": [
                    {"field": "paymentMode", "operator": "EQUALS", "value": "offline"},
                    {"field": "offlinePaymentMethod", "operator": "NOT_EQUALS", "value": "Cheque"}
                  ]
                },
                "screen": {
                  "title": "Registration Acknowledgement",
                  "message": "We acknowledge your registration for {{programName}}, a life-transforming 12-session experience with Mahatria.\n\n\nYour provisional registration number is: {{registrationNumber}}\n\n\nThe access details and recommended digital disciplines will be communicated to you a day before the commencement of the program.\n\n\nNote: Payment is subject to realization. A confirmation email along with the invoice will follow upon payment realization.\n\n\nLet this ''TAT'' magnetise the best of everything in your life.",
                  "variant": "info",
                  "showLogo": true,
                  "showBanner": true,
                  "logoUrl": "{{logoUrl}}",
                  "bannerImageUrl": "{{bannerImageUrl}}",
                  "actions": [
                    {
                      "actionKey": "HOME",
                      "label": "home",
                      "type": "secondary",
                      "apiKey": null
                    }
                  ]
                }
              },
              {
                "scenarioKey": "FREE_SEAT_REGISTRATION",
                "condition": {
                  "operator": "AND",
                  "conditions": [
                    {"field": "isFreeSeat", "operator": "EQUALS", "value": true},
                    {"field": "registrationStatus", "operator": "NOT_EQUALS", "value": "cancelled"}
                  ]
                },
                "screen": {
                  "title": "Registration Successful!",
                  "message": "Dear infinitheist {{seekerName}},\n\nYour registration for {{programName}} is successful.\n\nRegistration Number: {{registrationNumber}}\nProgram Date: {{programStartDate}} to {{programEndDate}}",
                  "variant": "success",
                  "showLogo": true,
                  "showBanner": true,
                  "logoUrl": "{{logoUrl}}",
                  "bannerImageUrl": "{{bannerImageUrl}}",
                  "actions": [
                    {
                      "actionKey": "HOME",
                      "label": "home",
                      "type": "secondary",
                      "apiKey": null
                    },
                    {
                      "actionKey": "VIEW_SUMMARY",
                      "label": "summary",
                      "type": "secondary",
                      "apiKey": "VIEW_REGISTRATION_SUMMARY"
                    }
                  ]
                }
              }
            ],
            "defaultScreen": {
              "title": "Payment Submitted!",
              "message": "Dear infinitheist {{seekerName}},\n\nYour payment for {{programName}} has been submitted successfully.\n\nRegistration Number: {{registrationNumber}}",
              "variant": "success",
              "showLogo": true,
              "showBanner": true,
              "logoUrl": "{{logoUrl}}",
              "bannerImageUrl": "{{bannerImageUrl}}",
              "actions": [
                {
                  "actionKey": "HOME",
                  "label": "home",
                  "type": "secondary",
                  "apiKey": 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'
);

-- ================================================
-- Link Variables to TAT TA26 Workflow
-- ================================================
DO $$
DECLARE
    v_workflow_id INT;
    v_var_id INT;
    v_order INT := 1;
BEGIN
    -- Get TAT TA26 workflow ID (corrected to match workflow key WF_TAT_TA26_V6)
    SELECT id INTO v_workflow_id FROM workflow_configuration WHERE workflow_key = 'WF_TAT_TA26_V6' LIMIT 1;
    
    IF v_workflow_id IS NOT NULL THEN
        -- Link relevant variables for TAT workflow (no travel variables needed)
        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',
              'PRO_FORMA_INVOICE_PDF_URL',
              'IS_FREE_SEAT_COMPUTED',
              'IS_WAITLISTED',
              'WAITLIST_POSITION',
              'INVOICE_GENERATED',
              'INVOICE_PDF_URL',
              'INVOICE_STATUS',
              'INVOICE_SEQUENCE_NUMBER',
              'REGISTRATION_NUMBER',
              'SEEKER_NAME',
              'SEEKER_EMAIL',
              'SEEKER_PHONE',
              'PROGRAM_FEE',
              'PROGRAM_NAME',
              'PROGRAM_START_DATE',
              'PROGRAM_END_DATE',
              'PROGRAM_REQUIRES_PAYMENT',
              'PROGRAM_ALLOWS_PROXY_REGISTRATION',
              'PROGRAM_HAS_TERMS',
              'LOGO_URL',
              'BANNER_IMAGE_URL',
              'OFFLINE_PAYMENT_METHOD',
              'RESERVED_LINK'
            )
            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 TAT TA26 workflow (ID: %)', v_order - 1, v_workflow_id;
    ELSE
        RAISE NOTICE 'TAT TA26 workflow not found, skipping variable linking';
    END IF;
END $$;

-- ================================================
-- Insert Session Tracking Configuration
-- ================================================
-- Note: TAT TA26 has 12 sessions. This section can be used to track session attendance if needed.
COMMENT ON TABLE workflow_configuration IS 'TAT TA26 has 12 weekly sessions from May 1 to July 17, 2026. Session tracking can be implemented separately if required.';

-- ================================================
-- Verification Query
-- ================================================
-- SELECT 
--   wc.id, 
--   wc.workflow_key, 
--   wc.workflow_name, 
--   wc.lifecycle_status,
--   COUNT(DISTINCT ws.id) as stage_count,
--   COUNT(DISTINCT 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_TAT_TA26_V6'
-- GROUP BY wc.id, wc.workflow_key, wc.workflow_name, wc.lifecycle_status;

-- ================================================
-- Session Details for Reference
-- ================================================
/*
TAT TA26 Sessions (12 weeks):
1. Session 1: May 1, 2026 (19:00-21:00 UTC)
2. Session 2: May 8, 2026 (19:00-21:00 UTC)
3. Session 3: May 15, 2026 (19:00-21:00 UTC)
4. Session 4: May 22, 2026 (19:00-21:00 UTC)
5. Session 5: May 29, 2026 (19:00-21:00 UTC)
6. Session 6: June 5, 2026 (19:00-21:00 UTC)
7. Session 7: June 12, 2026 (19:00-21:00 UTC)
8. Session 8: June 19, 2026 (19:00-21:00 UTC)
9. Session 9: June 26, 2026 (19:00-21:00 UTC)
10. Session 10: July 3, 2026 (19:00-21:00 UTC)
11. Session 11: July 10, 2026 (19:00-21:00 UTC)
12. Session 12: July 17, 2026 (19:00-21:00 UTC)

Each session is 2 hours long (7:00 PM - 9:00 PM IST / 1:30 PM - 3:30 PM UTC)
Mode: Online Webinar
Total Seats: 200
Waitlist Trigger: 20
Program Fee: {{programFee}} (includes GST)
*/