package ru.micord.ervu.account_applications.component.service;

import java.net.URI;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpMethod;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import ru.micord.ervu.account_applications.component.exception.IdmValidatorException;
import ru.micord.ervu.account_applications.security.context.SecurityContext;
import ru.micord.ervu.account_applications.service.constant.PathConstant;

/**
 * @author Emir Suleimanov
 */
public abstract class AbstractIdmValidatorService implements IdmValidatorService{
  protected RestTemplate restTemplate;
  protected SecurityContext securityContext;

  @Value("${idm.url}")
  protected String idmUrl;

  protected AbstractIdmValidatorService(RestTemplate restTemplate, SecurityContext securityContext) {
    this.restTemplate = restTemplate;
    this.securityContext = securityContext;
  }

  protected boolean checkExistsByQuery(String endpoint, String queryParamName, String queryParamValue) {
    URI uri = UriComponentsBuilder
        .fromHttpUrl(idmUrl)
        .pathSegment(PathConstant.PERSONS_PATH)
        .path(endpoint)
        .queryParam(queryParamName, queryParamValue)
        .build()
        .encode()
        .toUri();

    HttpHeaders headers = new HttpHeaders();
    headers.setBearerAuth(securityContext.getToken());
    HttpEntity<Void> request = new HttpEntity<>(headers);

    try {
      ResponseEntity<Boolean> response = restTemplate.exchange(
          uri,
          HttpMethod.GET,
          request,
          Boolean.class
      );

      return Boolean.TRUE.equals(response.getBody());
    }
    catch (Exception e) {
      throw new IdmValidatorException(String.format(
          "Ошибка при проверке значения [%s] через параметр [%s] по адресу [%s]",
          queryParamValue, queryParamName, uri
      ), e);
    }
  }
}
