package com.sonymusic.dx.dxuiservice.usm;

import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTDecodeException;
import java.util.Optional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * Session token related service.
 */
@Slf4j
@Service
public class USMSessionTokenService {

    /**
     * Details extracted from SME token.
     *
     * @param username User email address.
     * @param alias    User short name (alias).
     */
    public record TokenDetails(String username, String alias, String name, String family) {
    }

    /**
     * Extracts user id from valid SME JWT.
     *
     * @param jwt Sme JWT.
     * @return Optional of JWT subject or empty if not present.
     */
    public Optional<TokenDetails> extractTokenDetails(String jwt) {
        try {
            var decoded = JWT.decode(jwt);

            var alias = decoded.getSubject();
            var email = decoded.getClaim("email").asString();
            var name = decoded.getClaim("given_name").asString();
            var family = decoded.getClaim("family_name").asString();

            return Optional.of(new TokenDetails(email, alias, name, family));
        } catch (JWTDecodeException e) {
            log.error("JWT decode error", e);
            return Optional.empty();
        }
    }
}
