# 🎯 Complete API Payload Examples - All Endpoints

**Purpose**: Provides one complete, comprehensive example for each of the 5 main form endpoints.

---

## 🗺️ Quick Navigation

| Endpoint | Purpose | Main Use Cases |
|----------|---------|----------------|
| **GET /v1/program-templates?programType=TYPE** | Get templates by type | List all published templates for a program type |
| **GET /v1/program-templates/:id** | Get template by ID | View full template details including sections/questions |
| **POST /program/:id/form** | Create program form | Clone from template, clone from master, create custom, or mix |
| **PATCH /program/:id/form** | Update program form | Delete sections/questions, update existing, add new |
| **POST /program/:programId/sync-from-template** | Sync from template | REPLACE_ALL, MERGE, or ADD_NEW_ONLY strategies |
| **POST /v1/program-templates/:id/form** | Create template form | Clone from master, create custom, nested subsections |
| **PATCH /v1/program-templates/:id/form** | Update template form | Delete sections/questions, update existing, add new |
| **📂 Subsections** | Nested sections | Create hierarchical form structures with parent-child relationships |

---

## 🆕 GET /v1/program-templates?programType=TYPE - Get All Templates by Program Type

### 📝 What This Endpoint Does
Returns a list of all published templates for a given program type. Useful for program creation flows and template selection UIs.

### 🔗 Example Request
```
GET /v1/program-templates?programType=HDB
```

### 🏷️ Query Parameters
- `programType` (string, required): The program type key (e.g., `HDB`, `TAT`, etc.)
- `status` (optional): Filter by template status (e.g., `published`)

### 📦 Example Response
```json
[
  {
    "id": 2,
    "name": "HDB 2026 Standard",
    "programType": "HDB",
    "status": "published",
    "createdAt": "2026-01-10T12:00:00Z",
    "updatedAt": "2026-03-01T09:00:00Z"
  },
  {
    "id": 3,
    "name": "HDB Custom Variant",
    "programType": "HDB",
    "status": "published",
    "createdAt": "2026-02-15T08:30:00Z",
    "updatedAt": "2026-03-10T10:00:00Z"
  }
]
```

---

## 🆕 GET /v1/program-templates/:id - Get Template by Template ID

### 📝 What This Endpoint Does
Returns the full details of a specific template, including all sections and questions. Useful for template preview, editing, or cloning.

### 🔗 Example Request
```
GET /v1/program-templates/2
```

### 🏷️ Path Parameter
- `id` (number, required): The template ID

### 📦 Example Response
```json
{
  "id": 2,
  "name": "HDB 2026 Standard",
  "programType": "HDB",
  "status": "published",
  "createdAt": "2026-01-10T12:00:00Z",
  "updatedAt": "2026-03-01T09:00:00Z",
  "sections": [
    {
      "id": 10,
      "name": "Personal Details",
      "displayOrder": 1,
      "questions": [
        {
          "id": 100,
          "label": "Full Name",
          "type": "text",
          "config": { "isRequired": true }
        }
      ]
    }
  ]
}
```

---

## 📊 Form Hierarchy

```
Master (Global Library)
    ↓ clone
Template (Reusable Blueprint)
    ↓ clone
Program (Specific Instance)
```

**Clone Paths:**
- Template → Master (using `masterFormSectionId`)
- Program → Template (using `templateFormSectionId`)
- Program → Master (direct, using `masterFormSectionId`)

---

## 1️⃣ POST /program/:id/form - Create Program Form

### 📝 What This Endpoint Does
Creates a new registration form for a specific program. You can build forms by cloning from templates, from master sections, or creating custom sections from scratch.

### 🎯 Supported Use Cases

**Case 1: Clone All from Template** - Set `cloneFromTemplate: true` to automatically copy all sections and questions from a published template

**Case 2: Clone Specific Template Sections** - Select which template sections to clone by providing `templateFormSectionId` for each section

**Case 3: Clone from Master Sections** - Bypass template level and clone directly from master sections using `masterFormSectionId`

**Case 4: Create Custom Sections** - Build sections from scratch by providing `sectionName` and `sectionKey`

**Case 5: Mixed Approach** - Combine cloning and custom sections in the same request

**Override Options:**
- Use `sectionOverride` to customize cloned section properties (name, description, display order, conditional logic)
- Use `override` inside questions to customize cloned question properties (label, placeholder, config, options)

### Full Example with All Features

```json
{
  "programId": 23,
  "registrationLevel": "program",
  "sections": [
    {
      "templateFormSectionId": 6,
      "displayOrder": 1,
      "sectionOverride": {
        "sectionName": "Personal Information (Program Customized)",
        "sectionDescription": "Modified for this specific program",
        "displayOrder": 1,
        "isVisible": true,
        "conditionalConfig": {
          "showIf": { "field": "hasPassport", "value": "yes" }
        }
      },
      "questions": [
        {
          "templateQuestionId": 120,
          "displayOrder": 1
        },
        {
          "templateQuestionId": 121,
          "displayOrder": 2,
          "override": {
            "label": "Full Legal Name",
            "placeholder": "As per government ID",
            "helpText": "Enter your name exactly as shown on ID",
            "isVisible": true,
            "config": {
              "isRequired": true,
              "minCharacters": 3,
              "maxCharacters": 100,
              "pattern": "^[A-Za-z\\s]+$",
              "errorMessage": "Only alphabets allowed"
            }
          }
        }
      ]
    },
    {
      "masterFormSectionId": 3,
      "displayOrder": 2,
      "sectionOverride": {
        "sectionName": "Emergency Contact",
        "displayOrder": 2
      },
      "questions": [
        {
          "masterQuestionId": 115,
          "displayOrder": 1,
          "override": {
            "label": "Emergency Contact Name",
            "placeholder": "Enter full name",
            "config": {
              "isRequired": true,
              "maxCharacters": 100
            }
          }
        },
        {
          "masterQuestionId": 116,
          "displayOrder": 2,
          "override": {
            "config": {
              "isRequired": true
            },
            "optionConfig": [
              { "value": "mobile", "label": "Mobile", "selected": true },
              { "value": "home", "label": "Home Phone", "selected": false },
              { "value": "work", "label": "Work Phone", "selected": false }
            ]
          }
        }
      ]
    },
    {
      "sectionName": "Special Requirements",
      "sectionKey": "FS_SPECIAL_REQUIREMENTS",
      "sectionDescription": "Any special needs or accommodations",
      "displayOrder": 3,
      "conditionalConfig": {
        "showIf": { "field": "needsAccommodation", "value": "yes" }
      },
      "questions": [
        {
          "label": "Dietary Restrictions",
          "type": "multiselect",
          "answerType": "array",
          "displayOrder": 1,
          "config": {
            "isRequired": false,
            "minSelections": 0,
            "maxSelections": 5
          },
          "optionConfig": [
            { "value": "none", "label": "None" },
            { "value": "vegetarian", "label": "Vegetarian" },
            { "value": "vegan", "label": "Vegan" },
            { "value": "gluten_free", "label": "Gluten-Free" },
            { "value": "dairy_free", "label": "Dairy-Free" },
            { "value": "other", "label": "Other" }
          ]
        },
        {
          "label": "Additional Comments",
          "type": "textarea",
          "answerType": "string",
          "displayOrder": 2,
          "placeholder": "Please provide any additional details",
          "config": {
            "isRequired": false,
            "maxCharacters": 500
          }
        }
      ]
    }
  ],
  "createdBy": 9533
}
```

---

## 2️⃣ PATCH /program/:id/form - Update Program Form

### 📝 What This Endpoint Does
Updates an existing program form. Supports partial updates - you can delete sections, modify existing sections/questions, and add new sections/questions all in a single request.

### 🎯 Supported Operations

**Delete Operations:**
- `deleteSectionIds` - Remove entire sections (soft delete)
- `deleteQuestionIds` inside `updateSections` - Remove specific questions from a section

**Update Operations:**
- `updateSections` - Modify section metadata (name, description, display order, conditional logic)
- `updateQuestions` inside `updateSections` - Modify existing question properties

**Add Operations:**
- `addSections` - Add new sections (can clone from template/master or create custom)
- `addQuestions` inside `updateSections` - Add new questions to existing sections

**Combined Operations:**
You can combine all three operations in a single request for atomic updates.

### Full Example with All Operations

```json
{
  "programId": 1144,
  "registrationLevel": "program",
  "deleteSectionIds": [45, 46],
  "updateSections": [
    {
      "formSectionId": 41,
      "sectionName": "Participant Information (Revised)",
      "sectionDescription": "Updated description for clarity",
      "displayOrder": 1,
      "conditionalConfig": {
        "showIf": { "field": "isAdult", "value": "yes" }
      },
      "deleteQuestionIds": [1237, 1238],
      "updateQuestions": [
        {
          "programQuestionId": 1234,
          "label": "Full Name (As Per ID Proof)",
          "type": "text",
          "config": {
            "isRequired": true,
            "maxCharacters": 100,
            "pattern": "^[A-Za-z\\s]+$"
          },
          "displayOrder": 1
        },
        {
          "programQuestionId": 1235,
          "config": {
            "isRequired": false
          },
          "optionConfig": [
            { "value": "male", "label": "Male" },
            { "value": "female", "label": "Female" },
            { "value": "other", "label": "Other" },
            { "value": "prefer_not_to_say", "label": "Prefer not to say" }
          ],
          "displayOrder": 2
        }
      ],
      "addQuestions": [
        {
          "masterQuestionId": 55,
          "displayOrder": 3,
          "override": {
            "label": "Date of Birth",
            "placeholder": "DD/MM/YYYY",
            "config": {
              "isRequired": true,
              "dateFormat": "DD/MM/YYYY",
              "minAge": 18,
              "maxAge": 100
            }
          }
        },
        {
          "label": "Nationality",
          "type": "dropdown",
          "answerType": "string",
          "displayOrder": 4,
          "config": {
            "isRequired": true,
            "searchable": true
          },
          "optionConfig": [
            { "value": "IN", "label": "India" },
            { "value": "US", "label": "United States" },
            { "value": "UK", "label": "United Kingdom" },
            { "value": "CA", "label": "Canada" },
            { "value": "AU", "label": "Australia" }
          ]
        }
      ]
    },
    {
      "formSectionId": 42,
      "displayOrder": 2,
      "addQuestions": [
        {
          "masterQuestionId": 120,
          "displayOrder": 1
        }
      ]
    }
  ],
  "addSections": [
    {
      "templateFormSectionId": 10,
      "displayOrder": 3,
      "sectionOverride": {
        "sectionName": "Travel Details",
        "displayOrder": 3
      },
      "questions": [
        { "templateQuestionId": 150, "displayOrder": 1 },
        { "templateQuestionId": 151, "displayOrder": 2 }
      ]
    },
    {
      "sectionName": "Payment Information",
      "sectionKey": "FS_PAYMENT_INFO",
      "sectionDescription": "Payment and invoice details",
      "displayOrder": 4,
      "questions": [
        {
          "label": "Payment Method",
          "type": "radio",
          "answerType": "string",
          "displayOrder": 1,
          "config": {
            "isRequired": true
          },
          "optionConfig": [
            { "value": "card", "label": "Credit/Debit Card", "selected": true },
            { "value": "bank_transfer", "label": "Bank Transfer" },
            { "value": "upi", "label": "UPI" },
            { "value": "cash", "label": "Cash" }
          ]
        }
      ]
    }
  ],
  "updatedBy": 9533
}
```

---

## 3️⃣ POST /program/:programId/sync-from-template - Sync from Template

### 📝 What This Endpoint Does
Synchronizes a program form with its template, bringing in any changes made to the template after the program form was created. Useful for updating multiple programs when template structure changes.

### 🎯 Supported Sync Strategies

**REPLACE_ALL Strategy:**
- Deletes all existing program sections/questions
- Clones fresh copy from template
- Use when: Complete rebuild needed

**MERGE Strategy (Recommended):**
- Adds new sections/questions from template
- Updates existing items that match
- Keeps program-specific customizations
- Use when: Template evolved, want to preserve program customizations

**ADD_NEW_ONLY Strategy:**
- Only adds items that don't exist in program
- No updates or deletions
- Use when: Template has new sections but program has heavy customizations

**Additional Options:**
- `createBackup: true` - Creates soft-deleted snapshot before sync
- `previewOnly: true` - Returns diff without applying changes (useful for validation)
- `templateId` - Optional, uses program's linked template if not specified

### Full Example with All Options

```json
{
  "programId": 23,
  "templateId": 2,
  "strategy": "MERGE",
  "createBackup": true,
  "previewOnly": false
}
```

**Available Strategies:**

1. **REPLACE_ALL**: Deletes all existing sections/questions and clones fresh from template
2. **MERGE**: Adds new items from template, updates matching items, keeps extra program-specific items
3. **ADD_NEW_ONLY**: Only adds items that don't exist in the program (no updates or deletions)

**Preview Mode:**
- Set `previewOnly: true` to see what changes would be made without applying them
- Returns a diff showing additions, updates, and deletions

---

## 4️⃣ POST /v1/program-templates/:id/form - Create Template Form

### 📝 What This Endpoint Does
Creates a reusable form structure for a template. Templates serve as blueprints that multiple programs can clone from, ensuring consistency while allowing program-specific customizations.

### 🎯 Supported Use Cases

**Case 1: Clone from Master Sections** - Build template by cloning standard sections from the master library using `masterFormSectionId`

**Case 2: Clone with Section Overrides** - Customize cloned sections with template-specific names, descriptions, conditional logic using `sectionOverride`

**Case 3: Clone with Question Overrides** - Customize cloned questions with template-specific labels, validation, options using `override`

**Case 4: Create Custom Sections** - Build template-specific sections from scratch with `sectionName` and `sectionKey`

**Case 5: Nested Subsections** - Create hierarchical section structures using `subSections` array

**Case 6: Mixed Approach** - Combine cloning from master with custom sections in the same template

**Key Differences from Program Forms:**
- Templates clone from **master** (not from other templates)
- Templates serve as the **middle layer** between master and programs
- Changes to templates can be synced to programs using the sync endpoint

### Full Example with All Features

```json
{
  "programTemplateId": 2,
  "sections": [
    {
      "masterFormSectionId": 1,
      "displayOrder": 1,
      "sectionOverride": {
        "sectionName": "Basic Details (Template Version)",
        "sectionDescription": "Template-specific description",
        "displayOrder": 1,
        "isVisible": true,
        "conditionalConfig": {
          "showIf": { "field": "programType", "value": "residential" }
        }
      },
      "questions": [
        {
          "masterQuestionId": 2,
          "displayOrder": 1,
          "override": {
            "label": "Full Name (As per ID Proof)",
            "placeholder": "Enter your complete legal name",
            "helpText": "Name must match government-issued ID",
            "isVisible": true,
            "config": {
              "isRequired": true,
              "minCharacters": 3,
              "maxCharacters": 100,
              "pattern": "^[A-Za-z\\s]+$",
              "errorMessage": "Only alphabets and spaces allowed"
            }
          }
        },
        {
          "masterQuestionId": 3,
          "displayOrder": 2,
          "override": {
            "label": "Email Address",
            "config": {
              "isRequired": true,
              "pattern": "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$",
              "errorMessage": "Please enter a valid email address"
            }
          }
        },
        {
          "masterQuestionId": 4,
          "displayOrder": 3,
          "override": {
            "label": "Gender",
            "config": {
              "isRequired": true
            },
            "optionConfig": [
              { "value": "male", "label": "Male", "selected": false },
              { "value": "female", "label": "Female", "selected": false },
              { "value": "other", "label": "Other", "selected": false },
              { "value": "prefer_not_to_say", "label": "Prefer not to say", "selected": false }
            ]
          }
        }
      ]
    },
    {
      "masterFormSectionId": 2,
      "displayOrder": 2,
      "questions": [
        { 
          "masterQuestionId": 10,
          "displayOrder": 1
        },
        { 
          "masterQuestionId": 11,
          "displayOrder": 2,
          "override": {
            "config": {
              "isRequired": false
            }
          }
        }
      ]
    },
    {
      "sectionName": "Custom Template Section",
      "sectionKey": "FS_CUSTOM_TEMPLATE",
      "sectionDescription": "A section created directly in the template",
      "displayOrder": 3,
      "questions": [
        {
          "masterQuestionId": 50,
          "displayOrder": 1
        },
        {
          "label": "Program Experience Level",
          "type": "radio",
          "answerType": "string",
          "displayOrder": 2,
          "config": {
            "isRequired": true
          },
          "optionConfig": [
            { "value": "first_time", "label": "First Time Participant", "selected": false },
            { "value": "returning", "label": "Returning Participant", "selected": false },
            { "value": "advanced", "label": "Advanced Practitioner", "selected": false }
          ]
        }
      ],
      "subSections": [
        {
          "masterFormSectionId": 4,
          "displayOrder": 1,
          "questions": [
            { "masterQuestionId": 51, "displayOrder": 1 }
          ]
        }
      ]
    }
  ],
  "createdBy": 9533
}
```

---

## 5️⃣ PATCH /v1/program-templates/:id/form - Update Template Form

### 📝 What This Endpoint Does
Updates an existing template form structure. Supports partial updates - delete sections, modify existing sections/questions, and add new sections/questions all in one request. Changes can be synced to associated programs later.

### 🎯 Supported Operations

**Delete Operations:**
- `deleteSectionIds` - Remove entire sections from template (soft delete)
- `deleteQuestionIds` inside `updateSections` - Remove specific questions from a section

**Update Operations:**
- `updateSections` - Modify section metadata (name, description, display order, conditional logic)
- `updateQuestions` inside `updateSections` - Modify existing question properties (text, type, config, options)

**Add Operations:**
- `addSections` - Add new sections (clone from master or create custom)
- `addQuestions` inside `updateSections` - Add new questions to existing sections (clone from master or create custom)

**Combined Operations:**
You can combine all three operations in a single request for atomic template updates.

**Important:**
- Template updates do NOT automatically cascade to programs
- Use the sync endpoint to push template changes to programs
- This allows controlled rollout of template changes

### Full Example with All Operations

```json
{
  "programTemplateId": 2,
  "deleteSectionIds": [6, 7],
  "updateSections": [
    {
      "templateFormSectionId": 8,
      "name": "Updated Travel Information",
      "description": "Modified travel section description",
      "displayOrder": 1,
      "conditionalConfig": {
        "showIf": { "field": "needsTravel", "value": "yes" }
      },
      "deleteQuestionIds": [151, 152],
      "updateQuestions": [
        {
          "templateQuestionId": 153,
          "questionText": "Arrival Date and Time",
          "questionType": "datetime",
          "answerType": "datetime",
          "config": {
            "required": true,
            "minDate": "2026-04-01",
            "maxDate": "2026-12-31",
            "dateFormat": "YYYY-MM-DD",
            "timeFormat": "HH:mm"
          },
          "displayOrder": 1
        },
        {
          "templateQuestionId": 154,
          "questionText": "Departure Date and Time",
          "config": {
            "required": true
          },
          "optionConfig": [
            { "label": "Morning (6 AM - 12 PM)", "value": "morning" },
            { "label": "Afternoon (12 PM - 6 PM)", "value": "afternoon" },
            { "label": "Evening (6 PM - 10 PM)", "value": "evening" },
            { "label": "Late Night (10 PM onwards)", "value": "late_night" }
          ],
          "displayOrder": 2
        }
      ],
      "addQuestions": [
        {
          "masterQuestionId": 115,
          "displayOrder": 3,
          "override": {
            "label": "Travel Mode",
            "placeholder": "Select your mode of transport",
            "config": {
              "isRequired": true
            },
            "optionConfig": [
              { "value": "flight", "label": "Flight", "selected": false },
              { "value": "train", "label": "Train", "selected": false },
              { "value": "bus", "label": "Bus", "selected": false },
              { "value": "car", "label": "Personal Car", "selected": false },
              { "value": "other", "label": "Other", "selected": false }
            ]
          }
        },
        {
          "masterQuestionId": 116,
          "displayOrder": 4,
          "override": {
            "label": "Flight/Train Number (if applicable)",
            "placeholder": "e.g., AI 123 or 12345",
            "config": {
              "isRequired": false,
              "maxCharacters": 20,
              "conditionalLogic": {
                "showIf": { "questionId": 115, "value": ["flight", "train"] }
              }
            }
          }
        },
        {
          "label": "Pick-up Required?",
          "type": "radio",
          "answerType": "string",
          "displayOrder": 5,
          "config": {
            "isRequired": true
          },
          "optionConfig": [
            { "value": "yes", "label": "Yes, I need pick-up", "selected": false },
            { "value": "no", "label": "No, I will arrange my own transport", "selected": false }
          ]
        }
      ]
    },
    {
      "templateFormSectionId": 9,
      "displayOrder": 2,
      "addQuestions": [
        {
          "masterQuestionId": 120,
          "displayOrder": 1
        }
      ]
    }
  ],
  "addSections": [
    {
      "masterFormSectionId": 5,
      "displayOrder": 3,
      "sectionOverride": {
        "sectionName": "Accommodation Preferences",
        "displayOrder": 3
      },
      "questions": [
        { "masterQuestionId": 60, "displayOrder": 1 },
        { "masterQuestionId": 61, "displayOrder": 2 }
      ]
    },
    {
      "sectionKey": "FS_NEW_TEMPLATE_SECTION",
      "name": "Health & Medical Information",
      "description": "Medical conditions and emergency contacts",
      "displayOrder": 4,
      "conditionalConfig": {
        "showIf": { "field": "residentialProgram", "value": "yes" }
      },
      "questions": [
        {
          "label": "Do you have any medical conditions?",
          "type": "radio",
          "answerType": "string",
          "displayOrder": 1,
          "config": {
            "isRequired": true
          },
          "optionConfig": [
            { "value": "yes", "label": "Yes" },
            { "value": "no", "label": "No" }
          ]
        },
        {
          "label": "Please provide details",
          "type": "textarea",
          "answerType": "string",
          "displayOrder": 2,
          "placeholder": "Describe your medical condition, current medications, and any special care needed",
          "config": {
            "isRequired": true,
            "maxCharacters": 1000,
            "conditionalLogic": {
              "showIf": { "field": "medicalCondition", "value": "yes" }
            }
          }
        },
        {
          "masterQuestionId": 130,
          "displayOrder": 3,
          "override": {
            "label": "Blood Group",
            "config": {
              "isRequired": false
            },
            "optionConfig": [
              { "value": "a_positive", "label": "A+" },
              { "value": "a_negative", "label": "A-" },
              { "value": "b_positive", "label": "B+" },
              { "value": "b_negative", "label": "B-" },
              { "value": "o_positive", "label": "O+" },
              { "value": "o_negative", "label": "O-" },
              { "value": "ab_positive", "label": "AB+" },
              { "value": "ab_negative", "label": "AB-" },
              { "value": "unknown", "label": "Don't Know" }
            ]
          }
        }
      ]
    }
  ],
  "updatedBy": 9533
}
```

---

## � Subsections / Nested Sections

### 📝 What Are Subsections?
Subsections allow you to create hierarchical form structures where sections can contain child sections, enabling logical grouping and organization of related questions.

### 🎯 Key Concepts

**Hierarchy Levels:**
```
Parent Section
  ↓
  Child Section (Subsection Level 1)
    ↓
    Grandchild Section (Subsection Level 2)
      ↓
      ... (can nest further based on configuration)
```

**Use Cases:**
- Grouping related questions under a parent category
- Conditional sections that only appear under certain parent contexts
- Multi-step forms with logical progression
- Accordion-style UI components

### 🔧 How to Create Subsections

#### In POST Endpoints (Create)

**Example 1: Program Form with Subsections**
```json
{
  "programId": 23,
  "sections": [
    {
      "sectionName": "Travel Information",
      "sectionKey": "FS_TRAVEL_INFO",
      "displayOrder": 1,
      "questions": [
        {
          "label": "Do you need travel arrangements?",
          "type": "radio",
          "answerType": "string",
          "displayOrder": 1,
          "config": { "isRequired": true },
          "optionConfig": [
            { "value": "yes", "label": "Yes" },
            { "value": "no", "label": "No" }
          ]
        }
      ],
      "subSections": [
        {
          "sectionName": "Arrival Details",
          "sectionKey": "FS_ARRIVAL_DETAILS",
          "displayOrder": 1,
          "conditionalConfig": {
            "showIf": { "field": "needsTravel", "value": "yes" }
          },
          "questions": [
            {
              "label": "Arrival Date",
              "type": "date",
              "answerType": "date",
              "displayOrder": 1,
              "config": { "isRequired": true }
            },
            {
              "label": "Flight Number",
              "type": "text",
              "answerType": "string",
              "displayOrder": 2,
              "config": { "isRequired": false }
            }
          ]
        },
        {
          "sectionName": "Departure Details",
          "sectionKey": "FS_DEPARTURE_DETAILS",
          "displayOrder": 2,
          "conditionalConfig": {
            "showIf": { "field": "needsTravel", "value": "yes" }
          },
          "questions": [
            {
              "label": "Departure Date",
              "type": "date",
              "answerType": "date",
              "displayOrder": 1,
              "config": { "isRequired": true }
            }
          ],
          "subSections": [
            {
              "sectionName": "Return Flight Information",
              "sectionKey": "FS_RETURN_FLIGHT",
              "displayOrder": 1,
              "questions": [
                {
                  "label": "Return Flight Number",
                  "type": "text",
                  "answerType": "string",
                  "displayOrder": 1
                }
              ]
            }
          ]
        }
      ]
    }
  ],
  "createdBy": 9533
}
```

**Example 2: Template Form with Cloned Subsections**
```json
{
  "programTemplateId": 2,
  "sections": [
    {
      "masterFormSectionId": 10,
      "displayOrder": 1,
      "sectionOverride": {
        "sectionName": "Accommodation Requirements"
      },
      "questions": [
        { "masterQuestionId": 50, "displayOrder": 1 }
      ],
      "subSections": [
        {
          "masterFormSectionId": 11,
          "displayOrder": 1,
          "sectionOverride": {
            "sectionName": "Room Preferences"
          },
          "questions": [
            { "masterQuestionId": 60, "displayOrder": 1 },
            { "masterQuestionId": 61, "displayOrder": 2 }
          ]
        },
        {
          "masterFormSectionId": 12,
          "displayOrder": 2,
          "questions": [
            { "masterQuestionId": 70, "displayOrder": 1 }
          ]
        }
      ]
    }
  ],
  "createdBy": 9533
}
```

#### In PATCH Endpoints (Update)

**Adding Subsections to Existing Sections**
```json
{
  "programId": 1144,
  "updateSections": [
    {
      "formSectionId": 41,
      "addSubSections": [
        {
          "sectionName": "Additional Information",
          "sectionKey": "FS_ADDITIONAL_INFO",
          "displayOrder": 1,
          "questions": [
            {
              "label": "Any special requests?",
              "type": "textarea",
              "answerType": "string",
              "displayOrder": 1
            }
          ]
        }
      ]
    }
  ],
  "updatedBy": 9533
}
```

**Updating Existing Subsections**
```json
{
  "programId": 1144,
  "updateSections": [
    {
      "formSectionId": 41,
      "updateSubSections": [
        {
          "formSectionId": 55,
          "sectionName": "Updated Subsection Name",
          "displayOrder": 2,
          "addQuestions": [
            {
              "label": "New question in subsection",
              "type": "text",
              "answerType": "string",
              "displayOrder": 1
            }
          ]
        }
      ]
    }
  ],
  "updatedBy": 9533
}
```

### ⚙️ Subsection Rules & Constraints

**Display Order:**
- Each subsection has its own `displayOrder` relative to its siblings (other subsections at the same level)
- Subsection display order is independent of parent section's display order

**Nesting Depth:**
- Depth limit is controlled by `MAX_SECTION_NESTING_DEPTH` configuration
- If `null`: unlimited nesting allowed
- If a number (e.g., `3`): maximum 3 levels of nesting

**Conditional Logic:**
- Subsections can have their own `conditionalConfig`
- Parent section visibility affects child subsection visibility
- Child subsections inherit parent context but can have additional conditions

**Question Placement:**
- Parent sections can have questions at the parent level AND in subsections
- Questions in parent appear before subsection questions (unless display order specifies otherwise)

**Clone Behavior:**
- When cloning a section with `deepClone: true`, all subsections are included
- When cloning with `deepClone: false`, only the specified section is cloned (no children)

### 📋 Complete Subsection Example (3 Levels Deep)

```json
{
  "programId": 23,
  "sections": [
    {
      "sectionName": "Participant Details",
      "sectionKey": "FS_PARTICIPANT_DETAILS",
      "displayOrder": 1,
      "questions": [
        {
          "label": "Are you attending with family?",
          "type": "radio",
          "answerType": "string",
          "displayOrder": 1,
          "optionConfig": [
            { "value": "yes", "label": "Yes" },
            { "value": "no", "label": "No" }
          ]
        }
      ],
      "subSections": [
        {
          "sectionName": "Family Members",
          "sectionKey": "FS_FAMILY_MEMBERS",
          "displayOrder": 1,
          "conditionalConfig": {
            "showIf": { "field": "attendingWithFamily", "value": "yes" }
          },
          "questions": [
            {
              "label": "Number of family members",
              "type": "number",
              "answerType": "number",
              "displayOrder": 1
            }
          ],
          "subSections": [
            {
              "sectionName": "Spouse Details",
              "sectionKey": "FS_SPOUSE_DETAILS",
              "displayOrder": 1,
              "questions": [
                {
                  "label": "Spouse Name",
                  "type": "text",
                  "answerType": "string",
                  "displayOrder": 1
                }
              ],
              "subSections": [
                {
                  "sectionName": "Spouse Travel Details",
                  "sectionKey": "FS_SPOUSE_TRAVEL",
                  "displayOrder": 1,
                  "questions": [
                    {
                      "label": "Spouse traveling separately?",
                      "type": "radio",
                      "answerType": "string",
                      "displayOrder": 1,
                      "optionConfig": [
                        { "value": "yes", "label": "Yes" },
                        { "value": "no", "label": "No" }
                      ]
                    }
                  ]
                }
              ]
            },
            {
              "sectionName": "Children Details",
              "sectionKey": "FS_CHILDREN_DETAILS",
              "displayOrder": 2,
              "questions": [
                {
                  "label": "Number of children",
                  "type": "number",
                  "answerType": "number",
                  "displayOrder": 1
                }
              ]
            }
          ]
        }
      ]
    }
  ],
  "createdBy": 9533
}
```

### 🎨 UI Rendering Recommendations

**Hierarchical Display:**
```
📋 Participant Details
   └─ Are you attending with family? [Radio]
   
   📂 Family Members (Level 1 - conditional)
      └─ Number of family members [Number]
      
      📂 Spouse Details (Level 2)
         └─ Spouse Name [Text]
         
         📂 Spouse Travel Details (Level 3)
            └─ Spouse traveling separately? [Radio]
      
      📂 Children Details (Level 2)
         └─ Number of children [Number]
```

**Visual Indicators:**
- Use indentation or accordion UI for nested levels
- Show/hide subsections based on conditional logic
- Display breadcrumb trail for deep nesting
- Indicate required vs optional subsections

---

## �📊 Override Pattern Summary

### **Questions:**

#### In POST (when adding/cloning):
```json
{
  "masterQuestionId": 115,
  "displayOrder": 1,
  "override": {
    "label": "Custom Label",
    "placeholder": "Custom placeholder",
    "helpText": "Custom help text",
    "isVisible": true,
    "config": {
      "isRequired": true,
      "maxCharacters": 100
    },
    "optionConfig": [
      { "value": "yes", "label": "Yes" }
    ]
  }
}
```

**Note**: `displayOrder` is ONLY at the question level (direct field), NOT inside `override`.

#### In PATCH (when updating):
```json
{
  "programQuestionId": 1234,
  "label": "Direct update",
  "config": { "isRequired": false },
  "optionConfig": [{ "value": "no", "label": "No" }],
  "displayOrder": 2
}
```

---

### **Sections:**

#### In POST (when cloning from template/master):
```json
{
  "templateFormSectionId": 6,
  "displayOrder": 1,
  "sectionOverride": {
    "sectionName": "Overridden Name",
    "sectionDescription": "Overridden description",
    "isVisible": true,
    "conditionalConfig": { "showIf": { "field": "x", "value": "y" } }
  }
}
```

**Note**: `displayOrder` is ONLY at the section level (direct field), NOT inside `sectionOverride`.

#### In PATCH (when updating):
```json
{
  "formSectionId": 41,
  "sectionName": "Direct update",
  "sectionDescription": "Direct description update",
  "displayOrder": 2,
  "conditionalConfig": { "showIf": { "field": "a", "value": "b" } }
}
```

---

## ✅ Key Differences: POST vs PATCH

| Aspect | POST (Create/Clone) | PATCH (Update) |
|--------|---------------------|----------------|
| **Question Override** | Nested `override` object | Direct fields on question |
| **Section Override** | `sectionOverride` object | Direct fields on section |
| **Purpose** | Override cloned/master data | Update existing record |
| **Display Order** | Always present | Always present |

---

## 🔍 Display Order Consistency

**Display Order is maintained at ONE place (direct field):**

- **Questions**: `displayOrder` field at question level (NOT inside `override`)
- **Sections**: `displayOrder` field at section level (NOT inside `sectionOverride`)
- **Subsections**: `displayOrder` field at subsection level (relative to sibling subsections)

**Subsection Display Order Rules:**
- Each subsection's `displayOrder` is relative to its siblings at the same nesting level
- Parent section's display order does NOT affect subsection ordering
- Example: Parent Section (displayOrder: 1) can have:
  - Subsection A (displayOrder: 2)
  - Subsection B (displayOrder: 1) ← Will appear BEFORE Subsection A
- Display order within a nesting level is independent of parent levels

**⚠️ Important Note on Duplication:**

While the DTOs technically allow `displayOrder` inside `override` and `sectionOverride` objects, this creates confusion and is NOT recommended.

**Current Backend Behavior (if both are provided):**
```typescript
// Fallback priority (what the service uses):
finalDisplayOrder = override?.displayOrder ?? directDisplayOrder ?? auto-generated
```

**Best Practice - Use ONLY Direct Field:**
```json
✅ CORRECT:
{
  "masterQuestionId": 115,
  "displayOrder": 5,      // ← Only here
  "override": {
    "label": "Custom",
    "config": {...}       // ← NO displayOrder here
  }
}

❌ AVOID (confusing):
{
  "masterQuestionId": 115,
  "displayOrder": 5,      // ← Which one wins?
  "override": {
    "displayOrder": 10,   // ← Confusing!
    "config": {...}
  }
}
```

**Why Separate?**
- `displayOrder` = **WHERE** to place the item (positional)
- `override`/`sectionOverride` = **WHAT** content/config to modify (substantive)

**Consistency Rules:**
1. Every question MUST have `displayOrder` (direct field) when being created or updated
2. Every section MUST have `displayOrder` (direct field) when being created or updated
3. Display order determines the rendering sequence in the UI
4. Display order is unique within a section for questions
5. Display order is unique within a form for sections
6. **Never use `displayOrder` inside `override` or `sectionOverride` objects**

---

**Document Version**: 2.0  
**Last Updated**: March 26, 2026  
**Maintained By**: System Documentation
