package mx.gob.slp.baseadminweb.configuration.security;

import com.nimbusds.jwt.JWTParser;

final class CognitoDisplayNameResolver {

    private CognitoDisplayNameResolver() {
    }

    static String resolve(String idToken, String accessToken, String fallbackUsername) {
        String displayName = extractNameClaim(idToken);
        if (displayName == null || displayName.isBlank()) {
            displayName = extractNameClaim(accessToken);
        }
        if (displayName == null || displayName.isBlank()) {
            return fallbackUsername;
        }
        return displayName;
    }

    private static String extractNameClaim(String token) {
        if (token == null || token.isBlank()) {
            return null;
        }
        try {
            return JWTParser.parse(token).getJWTClaimsSet().getStringClaim("name");
        } catch (Exception ex) {
            return null;
        }
    }
}