package ervu_business_metrics.kafka.listener;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import ervu_business_metrics.config.KafkaEnabledCondition;
import ervu_business_metrics.model.sso.AuthEventResponse;
import ervu_business_metrics.service.FailedAuthService;
import exception.JsonParseException;
import org.springframework.context.annotation.Conditional;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

/**
 * @author gulnaz
 */
@Component
@Conditional(KafkaEnabledCondition.class)
public class FailedAuthListener {
  private static final String FAILED_AUTH_EVENT = "USER_AUTHENTICATION_ERROR";

  private final ObjectMapper objectMapper;
  private final FailedAuthService failedAuthService;

  public FailedAuthListener(ObjectMapper objectMapper, FailedAuthService failedAuthService) {
    this.objectMapper = objectMapper;
    this.failedAuthService = failedAuthService;
  }

  @KafkaListener(id = "${kafka.auth.events.group.id}", topics = "${kafka.sso.auth.events.response}")
  public void listenFailedAuthEvent(String kafkaMessage) {
    AuthEventResponse response;

    try {
      response = objectMapper.readValue(kafkaMessage, AuthEventResponse.class);
    }
    catch (JsonProcessingException e) {
      throw new JsonParseException(e);
    }

    if (response.userId() != null && FAILED_AUTH_EVENT.equals(response.eventType())) {
      failedAuthService.save(response);
    }
  }
}
