public class RiabuAuthAccessToken {
 
    public static String getAccessToken() {
 
        RIABU_Integration__mdt config = RIABU_Integration__mdt.getInstance('Riabu_Record');
 
        System.debug('🔄 Token expired or unavailable. Requesting new token...');
 
        HttpRequest req = new HttpRequest();
        req.setEndpoint(config.Endpoint__c + '/api/v1/oauth/token');
        req.setMethod('POST');
        req.setHeader('Content-Type', 'application/json');
 
 
        Map<String, String> payload = new Map<String, String>();
        			payload.put('username', config.Username__c);
                    payload.put('client_id',config.Client_Id__c);
                    payload.put('client_secret',config.Client_Secret__c);
                    payload.put('password', config.Password__c);
        			payload.put('grant_type', config.Grant_Type__c);
        req.setBody(JSON.serialize(payload));
 
 
        Http http = new Http();
        HttpResponse res = http.send(req);
 
        System.debug('📥 Token Response: ' + res.getBody());
 
        if (res.getStatusCode() != 200) {
            System.debug('❌ Token generation failed');
            return null;
        }
 
        Map<String, Object> tokenMap = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
 
        String newAccessToken   = (String) tokenMap.get('access_token');
        String newRefreshToken  = (String) tokenMap.get('refresh_token');
 
        System.enqueueJob(new RiabuTokenUpdateJob('Riabu_Record', newAccessToken, newRefreshToken));
 
        System.debug('✅ Token refreshed and CMDT update queued');
 
        return newAccessToken;
    }
}