package com.hepl.tunefortwo.config.security;

import java.util.Map;

import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.stereotype.Component;

import com.hepl.tunefortwo.entity.Users;

@Component
public class JWTHelper {

    private final JwtDecoder jwtDecoder;

    public JWTHelper(JwtDecoder jwtDecoder) {
        this.jwtDecoder = jwtDecoder;
    }

    public Map<String, Object> getDetails(Authentication authentication) {
        Jwt jwt = (Jwt) authentication.getPrincipal();
        Jwt decode = jwtDecoder.decode(jwt.getTokenValue());
        return decode.getClaimAsMap("userDetails");
    }

    public Users getUserDetail(Authentication authentication) {
        Map<String, Object> details = getDetails(authentication);
        Users user = new Users();
        user.setId(details.get("_id").toString());
        user.setUserId(details.get("userId").toString());
        user.setUsername(details.get("username").toString());

        return user;
    }

    public boolean isSecretary(Authentication authentication) {
        Map<String, Object> details = (Map<String, Object>) getDetails(authentication).get("role");
        return details.get("name").toString().equalsIgnoreCase("Secretary");
    }

}
