package test.kar.karideo;

import java.io.IOException;

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.api.extension.ExtendWith;
import org.kar.archidata.exception.RESTErrorResponseException;
import org.kar.archidata.tools.ConfigBaseVariable;
import org.kar.archidata.tools.RESTApi;
import org.kar.karideo.api.HealthCheck.HealthResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@ExtendWith(StepwiseExtension.class)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class TestHealthCheck {
	private final static Logger LOGGER = LoggerFactory.getLogger(TestHealthCheck.class);

	static WebLauncherTest webInterface = null;
	static RESTApi api = null;

	@BeforeAll
	public static void configureWebServer() throws Exception {
		LOGGER.info("configure server ...");
		webInterface = new WebLauncherTest();
		LOGGER.info("Create DB");
		try {
			webInterface.migrateDB();
		} catch (final Exception ex) {
			ex.printStackTrace();
			LOGGER.error("Detect an error: {}", ex.getMessage());
		}
		LOGGER.info("Start REST (BEGIN)");
		webInterface.process();
		LOGGER.info("Start REST (DONE)");
		api = new RESTApi(ConfigBaseVariable.apiAdress);
	}

	@AfterAll
	public static void stopWebServer() throws InterruptedException, IOException {
		LOGGER.info("Kill the web server");
		webInterface.stop();
		webInterface = null;
		LOGGER.info("Remove the test db");
		// DBEntry.closeAllForceMode();
		ConfigBaseVariable.clearAllValue();
	}

	@Order(1)
	@Test
	// @RepeatedTest(10)
	public void checkHealthCheck() throws Exception {
		final HealthResult result = api.get(HealthResult.class, "health_check");
		Assertions.assertEquals(result.value(), "alive and kicking");
	}

	@Order(2)
	@Test
	public void checkHealthCheckWrongAPI() throws Exception {
		Assertions.assertThrows(RESTErrorResponseException.class, () -> api.get(HealthResult.class, "health_checks"));
	}

}
