package ervu_dashboard.security.provider;

import ervu_dashboard.security.model.jwt.UserSession;
import ervu_dashboard.security.model.jwt.authentication.JwtTokenAuthentication;
import ervu_dashboard.security.model.jwt.authentication.JwtTokenDummy;
import ervu_dashboard.security.service.JwtTokenService;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

@Component
public class ErvuJwtAuthenticationProvider implements AuthenticationProvider {

  private final JwtTokenService jwtTokenService;

  public ErvuJwtAuthenticationProvider(JwtTokenService jwtTokenService) {
    this.jwtTokenService = jwtTokenService;
  }

  @Override
  public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    JwtTokenDummy jwtTokenDummy = (JwtTokenDummy) authentication;
    String jwtToken = jwtTokenDummy.getToken();
    UserSession userSession = jwtTokenService.getUserSession(jwtToken);
    return new JwtTokenAuthentication(userSession);
  }

  @Override
  public boolean supports(Class<?> authentication) {
    return JwtTokenDummy.class.isAssignableFrom(authentication);
  }
}
