public class RiabuContactSync {

    public static String syncContacts(String riabuCustomerId) {

        System.debug(' START — RiabuContactSync for CustomerId: ' + riabuCustomerId);

        // Load Integration Config
        RIABU_Integration__mdt config = [
            SELECT Access_Token__c, Refresh_Token__c, RIABU_Fetch_Contacts_Endpoint__c
            FROM RIABU_Integration__mdt
            WHERE DeveloperName = 'Riabu_Record'
            LIMIT 1
        ];

        if (config == null || config.RIABU_Fetch_Contacts_Endpoint__c == null) {
            return 'Config or endpoint missing from Metadata';
        }

        String baseEndpoint = config.RIABU_Fetch_Contacts_Endpoint__c;
        if (!baseEndpoint.endsWith('/')) {
            baseEndpoint += '/';
        }

        String endpoint = baseEndpoint + riabuCustomerId;
        System.debug(' Corrected Request Endpoint: ' + endpoint);

        HttpRequest req = new HttpRequest();
        req.setEndpoint(endpoint);
        req.setMethod('GET');

        if (String.isBlank(config.Access_Token__c)) {
            System.debug('Access Token missing — Generating new token');
            RiabuAuthAccessToken.getAccessToken();
        }

        req.setHeader('Authorization', 'Bearer ' + config.Access_Token__c);

        Http http = new Http();
        HttpResponse res = http.send(req);

        System.debug('Response Status: ' + res.getStatusCode());
        System.debug('Body: ' + res.getBody());

        if (res.getStatusCode() != 200) {
            return 'Riabu Contact Fetch Error: ' + res.getStatus();
        }

        // Parse JSON
        Map<String, Object> root = (Map<String, Object>)
            JSON.deserializeUntyped(res.getBody());

        if (root == null || root.get('data') == null) {
            return 'Invalid data from Riabu API';
        }

        Map<String, Object> data = (Map<String, Object>) root.get('data');
        Map<String, Object> model = (Map<String, Object>) data.get('model');

        if (model == null) {
            return 'No Contact Model Received';
        }

        System.debug('Riabu Contact: ' + model);

        // Ensure Account exists
        Account acc;
        try {
            acc = [
                SELECT Id
                FROM Account
                WHERE RIABU_Customer_ID__c = :riabuCustomerId
                LIMIT 1
            ];
        } catch (Exception e) {
            return 'No matching Salesforce Account';
        }

        String riabuContactId = String.valueOf(model.get('id'));

        Contact con = new Contact();
        con.RIABU_Contact_ID__c = riabuContactId;
        con.LastName  = String.valueOf(model.get('accounts_payable_contact_name'));
        con.Phone     = String.valueOf(model.get('accounts_payable_phone_number'));
        con.Email     = String.valueOf(model.get('accounts_payable_email_address'));
        con.Invoice_Email__c = String.valueOf(model.get('email_to_send_e_invoices_to'));
        con.isPrimary__c = true;
        con.AccountId = acc.Id;

        // Use UPSERT with external Id (safe duplicate handling)
        ContactTriggerHandler.becamePrimary = false;
        upsert con RIABU_Contact_ID__c;

        return 'Contact synced successfully! Riabu ID: ' + riabuContactId;
    }
}