public class RiabuAccountSync {
 
    public static String insertAccounts() {
 
        RIABU_Integration__mdt config = [
            SELECT Access_Token__c, Refresh_Token__c, Endpoint__c, RIABU_Fetch_Accounts_Endpoint__c
            FROM RIABU_Integration__mdt
            WHERE DeveloperName = 'Riabu_Record'
            LIMIT 1
        ];
 
        HttpRequest req = new HttpRequest();
        req.setEndpoint(config.RIABU_Fetch_Accounts_Endpoint__c);
        req.setMethod('GET');
 
        if (config.Access_Token__c == null) {
            RiabuAuthAccessToken.getAccessToken();
        }
 
        req.setHeader('Authorization', 'Bearer ' + config.Access_Token__c);
 
        Http http = new Http();
        HttpResponse res = http.send(req);
 
        if (res.getStatusCode() != 200) {
            return 'Invalid Field Callout';
        }
 
        Map<String, Object> root = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
        List<Object> dataList = (List<Object>) root.get('data');
 
        if (dataList == null || dataList.isEmpty()) {
            return 'No Data Returned';
        }
 
        // step 1: collect incoming riabu ids
        Set<String> incomingIds = new Set<String>();
        for (Object o : dataList) {
            Map<String, Object> item = (Map<String, Object>) o;
            incomingIds.add(String.valueOf(item.get('id')));
        }
 
        // step 2: fetch existing SF accounts
        Map<String, Account> existingMap = new Map<String, Account>();
 
        if (!incomingIds.isEmpty()) {
            for (Account acc : [
                SELECT Id, RIABU_Customer_ID__c
                FROM Account
                WHERE RIABU_Customer_ID__c IN :incomingIds
            ]) {
                existingMap.put(acc.RIABU_Customer_ID__c, acc);
            }
        }
 
        // step 3: build list of new accounts
        Set<String> processedIds = new Set<String>();
        List<Account> toInsert = new List<Account>();
 
        for (Object o : dataList) {
            Map<String, Object> item = (Map<String, Object>) o;
            String riabuId = String.valueOf(item.get('id'));
 
            if (riabuId == null) continue;
 
            // skip duplicates in API response
            if (processedIds.contains(riabuId)) continue;
            processedIds.add(riabuId);
 
            // skip existing SF accounts
            if (existingMap.containsKey(riabuId)) {
                System.debug('[' + riabuId + '] ALREADY EXISTS IN SALESFORCE');
                continue;
            }
 
            // insert new
            Account a = new Account();
            a.Name = (String) item.get('name');
            a.RIABU_Customer_ID__c = riabuId;
            a.Days_to_Pay__c = (Integer) item.get('agreed_credit_terms_day');
            toInsert.add(a);
 
            System.debug('[' + riabuId + '] Record Inserted ***');
        }
 
        // step 4: insert
        if (!toInsert.isEmpty()) {
            insert toInsert;
            return toInsert.size() + ' new records inserted';
        }
 
        return 'No new records';
    }
}