package cz.muni.ics.oidc.server.ga4gh;

import com.nimbusds.jwt.JWTClaimsSet;
import cz.muni.ics.oidc.server.PerunAccessTokenEnhancer;
import cz.muni.ics.openid.connect.model.UserInfo;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import static cz.muni.ics.oidc.server.ga4gh.Ga4ghApiClaimSource.GA4GH_SCOPE;

/**
 * Implements changes required by GA4GH specification.
 *
 * @author Martin Kuba <makub@ics.muni.cz>
 */
@SuppressWarnings("unused")
@Slf4j
@NoArgsConstructor
public class Ga4ghAccessTokenModifier implements PerunAccessTokenEnhancer.AccessTokenClaimsModifier {

	@Override
	public void modifyClaims(String sub,
							 JWTClaimsSet.Builder builder,
							 OAuth2AccessToken accessToken,
							 OAuth2Authentication authentication,
							 UserInfo userInfo)
	{
		Set<String> scopes = accessToken.getScope();
		//GA4GH
		if (scopes.contains(GA4GH_SCOPE)) {
			Object originalAud = builder.getClaims().get("aud");
			Set<String> newAud = new HashSet<>();
			if (originalAud instanceof String) {
				newAud.add((String) originalAud);
			} else if (originalAud instanceof Collection) {
				newAud.addAll((Collection<String>) originalAud);
			}
			log.debug("Adding claims required by GA4GH to access token");
			builder.audience(new ArrayList<>(newAud));
		}
	}

}
