/***********************************************************************************************************
 * Name         : NR_RestReceiveData
 * Purpose      : Rest Service to upsert Contributors and update Societies from PROD
 **********************************************************************************************************/
@RestResource(urlMapping='/NR_ReceiveData/*')
global class NR_RestReceiveData {
    @HttpPost
    global static void postReceiveRecords() {
        RestResponse response = RestContext.response;
        ReceiveDataResult result = new ReceiveDataResult();
        try {
            String requestBody = RestContext.request.requestBody.toString();

            List<SObject> sObjects = (List<SObject>) JSON.deserialize(requestBody, List<SObject>.class);
            result.received = sObjects.size();
            if (!sObjects.isEmpty() && sObjects[0] instanceof Contributor__c) {
                result.sObjectType = 'Contributor__c';
                result = NR_RestReceiveDataHelper.upsertContributors(sObjects);
            } else {
                result.sObjectType = 'Society__c';
                result = NR_RestReceiveDataHelper.updateSocieties(sObjects);
            }
            response.statusCode = 200;
        } catch (Exception ex) {
            ErrorLogger.logError(ex);
            result.errors = new List<String>{ ex.getMessage() };
            response.statusCode = 400;
        } finally {
            response.responseBody = Blob.valueOf(JSON.serializePretty(result));
        }
    }

    public class ReceiveDataResult {
        public String sObjectType;
        public Integer received;
        public Integer updated;
        public Integer inserted;
        public Integer failedUpdates;
        public Integer failedInserts;
        public List<String> errors;

        public ReceiveDataResult() {
            this.sObjectType = null;
            this.received = 0;
            this.updated = 0;
            this.inserted = 0;
            this.failedUpdates = 0;
            this.failedInserts = 0;
            this.errors = new List<String>();
        }

        public ReceiveDataResult(String sObjectType, Integer received, Integer updated, Integer inserted) {
            this.sObjectType = sObjectType;
            this.received = received;
            this.updated = updated;
            this.inserted = inserted;
            this.failedUpdates = 0;
            this.failedInserts = 0;
            this.errors = new List<String>();
        }
    }
}