package com.example.demo;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

public class CustomTokenConverter extends JwtAccessTokenConverter {

    @Value("#{'${user.oauth.user.roles}'.split(',')}")
    private List<String> roles;

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken,
                                     OAuth2Authentication authentication) {
        //     if(authentication.getOAuth2Request().getGrantType().equalsIgnoreCase("password")) {
        User user = (User) authentication.getPrincipal();
        System.out.println(user);
        final Map<String, Object> additionalInfo = new HashMap<>();
        additionalInfo.put("email", user.getUsername());
        additionalInfo.put("sub", "To be filled somehow by client");
        additionalInfo.put("authorities", authentication.getUserAuthentication().getAuthorities().stream().map(
                GrantedAuthority::getAuthority
        ).collect(Collectors.toList())); // "authorities": ["chemaxon", ...]
        additionalInfo.put("roles", roles);
        ((DefaultOAuth2AccessToken) accessToken)
                .setAdditionalInformation(additionalInfo);
        //      }
        accessToken = super.enhance(accessToken, authentication);
        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(new HashMap<>());
        return accessToken;
    }
}
