/*
 * Copyright 2012-present the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.boot.elasticsearch.health;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import co.elastic.clients.transport.rest5_client.low_level.Request;
import co.elastic.clients.transport.rest5_client.low_level.Response;
import co.elastic.clients.transport.rest5_client.low_level.Rest5Client;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.io.entity.BasicHttpEntity;
import org.junit.jupiter.api.Test;

import org.springframework.boot.health.contributor.Health;
import org.springframework.boot.health.contributor.Status;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;

/**
 * Tests for {@link ElasticsearchRestClientHealthIndicator}.
 *
 * @author Artsiom Yudovin
 * @author Filip Hrisafov
 */
class ElasticsearchRestClientHealthIndicatorTests {

	private final Rest5Client restClient = mock(Rest5Client.class);

	private final ElasticsearchRestClientHealthIndicator elasticsearchRestClientHealthIndicator = new ElasticsearchRestClientHealthIndicator(
			this.restClient);

	@Test
	void elasticsearchIsUp() throws IOException {
		BasicHttpEntity httpEntity = new BasicHttpEntity(
				new ByteArrayInputStream(createJsonResult(200, "green").getBytes()), ContentType.APPLICATION_JSON);
		Response response = mock(Response.class);
		given(response.getStatusCode()).willReturn(200);
		given(response.getEntity()).willReturn(httpEntity);
		given(this.restClient.performRequest(any(Request.class))).willReturn(response);
		org.springframework.boot.health.contributor.Health health = this.elasticsearchRestClientHealthIndicator
			.health();
		assertThat(health.getStatus()).isEqualTo(Status.UP);
		assertHealthDetailsWithStatus(health.getDetails(), "green");
	}

	@Test
	void elasticsearchWithYellowStatusIsUp() throws IOException {
		BasicHttpEntity httpEntity = new BasicHttpEntity(
				new ByteArrayInputStream(createJsonResult(200, "yellow").getBytes()), ContentType.APPLICATION_JSON);
		Response response = mock(Response.class);
		given(response.getStatusCode()).willReturn(200);
		given(response.getEntity()).willReturn(httpEntity);
		given(this.restClient.performRequest(any(Request.class))).willReturn(response);
		Health health = this.elasticsearchRestClientHealthIndicator.health();
		assertThat(health.getStatus()).isEqualTo(Status.UP);
		assertHealthDetailsWithStatus(health.getDetails(), "yellow");
	}

	@Test
	void elasticsearchIsDown() throws IOException {
		given(this.restClient.performRequest(any(Request.class))).willThrow(new IOException("Couldn't connect"));
		Health health = this.elasticsearchRestClientHealthIndicator.health();
		assertThat(health.getStatus()).isEqualTo(Status.DOWN);
		assertThat(health.getDetails()).contains(entry("error", "java.io.IOException: Couldn't connect"));
	}

	@Test
	void elasticsearchIsDownByResponseCode() throws IOException {
		Response response = mock(Response.class);
		given(response.getStatusCode()).willReturn(500);
		given(response.getWarnings()).willReturn(List.of("Bad things happened"));
		given(this.restClient.performRequest(any(Request.class))).willReturn(response);
		Health health = this.elasticsearchRestClientHealthIndicator.health();
		assertThat(health.getStatus()).isEqualTo(Status.DOWN);
		assertThat(health.getDetails()).contains(entry("statusCode", 500),
				entry("warnings", List.of("Bad things happened")));
	}

	@Test
	void elasticsearchIsOutOfServiceByStatus() throws IOException {
		BasicHttpEntity httpEntity = new BasicHttpEntity(
				new ByteArrayInputStream(createJsonResult(200, "red").getBytes()), ContentType.APPLICATION_JSON);
		Response response = mock(Response.class);
		given(response.getStatusCode()).willReturn(200);
		given(response.getEntity()).willReturn(httpEntity);
		given(this.restClient.performRequest(any(Request.class))).willReturn(response);
		Health health = this.elasticsearchRestClientHealthIndicator.health();
		assertThat(health.getStatus()).isEqualTo(Status.OUT_OF_SERVICE);
		assertHealthDetailsWithStatus(health.getDetails(), "red");
	}

	private void assertHealthDetailsWithStatus(Map<String, Object> details, String status) {
		assertThat(details).contains(entry("cluster_name", "elasticsearch"), entry("status", status),
				entry("timed_out", false), entry("number_of_nodes", 1), entry("number_of_data_nodes", 1),
				entry("active_primary_shards", 0), entry("active_shards", 0), entry("relocating_shards", 0),
				entry("initializing_shards", 0), entry("unassigned_shards", 0), entry("delayed_unassigned_shards", 0),
				entry("number_of_pending_tasks", 0), entry("number_of_in_flight_fetch", 0),
				entry("task_max_waiting_in_queue_millis", 0), entry("active_shards_percent_as_number", 100.0),
				entry("unassigned_primary_shards", 10));
	}

	private String createJsonResult(int responseCode, String status) {
		if (responseCode == 200) {
			return String.format("{\"cluster_name\":\"elasticsearch\","
					+ "\"status\":\"%s\",\"timed_out\":false,\"number_of_nodes\":1,"
					+ "\"number_of_data_nodes\":1,\"active_primary_shards\":0,"
					+ "\"active_shards\":0,\"relocating_shards\":0,\"initializing_shards\":0,"
					+ "\"unassigned_shards\":0,\"delayed_unassigned_shards\":0,"
					+ "\"number_of_pending_tasks\":0,\"number_of_in_flight_fetch\":0,"
					+ "\"task_max_waiting_in_queue_millis\":0,\"active_shards_percent_as_number\":100.0,"
					+ "\"unassigned_primary_shards\": 10 }", status);
		}
		return "{\n  \"error\": \"Server Error\",\n  \"status\": " + responseCode + "\n}";
	}

}
