/**
 * @description Builds CLM-ready JSON payload for Appraiser Case with related Deficiencies.
 * Used to transform Salesforce data into DocuSign CLM merge field structure.
 */
public class AppraiserCasePayloadBuilder {
    
    /**
     * @description Generates CLM merge payload for a given Appraiser Case.
     * @param caseId Appraiser_Case__c record Id
     * @return Map<String, Object> CLM merge data ready for template rendering
     */
    public static Map<String, Object> buildPayload(String caseId) {
        // Query parent case with all child deficiencies
        Appraiser_Case__c appraiserCase = queryAppraiserCase(caseId);
        
        if (appraiserCase == null) {
            throw new IllegalArgumentException('Appraiser Case not found: ' + caseId);
        }
        
        // Build CLM payload structure
        Map<String, Object> payload = new Map<String, Object>();
        payload.put('AppraiserCaseNumber', appraiserCase.Name);
        payload.put('AppraiserFieldReviewDate', formatDate(appraiserCase.Appraiser_Field_Review_Date__c));
        payload.put('PropertyAddress', appraiserCase.Property_Address__c);
        
        // Transform child deficiencies into DeficiencyList array
        List<Map<String, Object>> deficiencyList = new List<Map<String, Object>>();
        if (appraiserCase.Deficiencies__r != null && !appraiserCase.Deficiencies__r.isEmpty()) {
            for (Appraiser_Case_Deficiency__c deficiency : appraiserCase.Deficiencies__r) {
                Map<String, Object> defMap = new Map<String, Object>();
                defMap.put('deficiencyNumber', deficiency.Deficiency_Number__c);
                defMap.put('description', deficiency.Description__c);
                defMap.put('resolution', deficiency.Resolution__c);
                deficiencyList.add(defMap);
            }
        }
        payload.put('DeficiencyList', deficiencyList);
        
        return payload;
    }
    
    /**
     * @description Returns CLM payload as JSON string for API transmission.
     * @param caseId Appraiser_Case__c record Id
     * @return String JSON representation of payload
     */
    public static String buildPayloadJson(String caseId) {
        Map<String, Object> payload = buildPayload(caseId);
        return JSON.serialize(payload);
    }
    
    /**
     * @description Query Appraiser Case with related Deficiencies ordered by number.
     * @param caseId Appraiser_Case__c record Id
     * @return Appraiser_Case__c Record with Deficiencies__r populated
     */
    private static Appraiser_Case__c queryAppraiserCase(String caseId) {
        List<Appraiser_Case__c> results = [
            SELECT 
                Id, 
                Name, 
                Appraiser_Field_Review_Date__c, 
                Property_Address__c,
                (SELECT Id, Deficiency_Number__c, Description__c, Resolution__c 
                 FROM Deficiencies__r 
                 ORDER BY Deficiency_Number__c ASC)
            FROM Appraiser_Case__c
            WHERE Id = :caseId
            LIMIT 1
        ];
        
        return results.isEmpty() ? null : results.get(0);
    }
    
    /**
     * @description Format date for CLM merge (YYYY-MM-DD or null).
     * @param dt Date field value
     * @return String Formatted date or null
     */
    private static String formatDate(Date dt) {
        return dt != null ? dt.format() : null;
    }
}
