package org.egl_cepgl.pm.config;

import org.springframework.core.convert.converter.Converter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.jwt.Jwt;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class CustomJwtGrantedAuthoritiesConverter implements Converter<Jwt, Collection<GrantedAuthority>> {

    private final String clientName;

    public CustomJwtGrantedAuthoritiesConverter(String clientName) {
        this.clientName = clientName;
    }

    @Override
    public Collection<GrantedAuthority> convert(Jwt jwt) {
        Map<String, Object> resourceAccess = jwt.getClaimAsMap("resource_access");

        if (resourceAccess != null && resourceAccess.containsKey(clientName)) {
            Map<String, Object> clientResource = (Map<String, Object>) resourceAccess.get(clientName);
            if (clientResource != null && clientResource.containsKey("roles")) {
                List<String> clientRoles = (List<String>) clientResource.get("roles");
                return clientRoles.stream()
                        .map(role -> new SimpleGrantedAuthority("ROLE_" + role))
                        .collect(Collectors.toList());
            }
        }
        return Collections.emptyList();
    }
}
