/*
 * Copyright 2018 Scytl Secure Electronic Voting SA
 *
 * All rights reserved
 *
 * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
 */
package com.scytl.products.ov.vm.ui.ws.rs.application.operation;

import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.scytl.products.ov.commons.infrastructure.health.HealthCheckRegistry;
import com.scytl.products.ov.commons.infrastructure.health.HealthCheckStatus;
import com.scytl.products.ov.commons.infrastructure.health.HealthCheckValidationType;

import java.util.Arrays;

/**
 * REST Service for connectivity validation purposes
 */
@Stateless(name = "vmCheckHealth")
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
@Path("check")
public class CheckHealthResource {

	@Inject
	private HealthCheckRegistry healthCheckRegistry;

	private static final String READY_PATH = "ready";

	/**
	 * Runs all registered Health checks.
	 *
	 * @return Returns an HTTP Status code 200, if all health checks are ok, 503 if any has failed
	 */
	@GET
	@Produces(MediaType.APPLICATION_JSON)
	public Response getStatus() {
		final HealthCheckStatus serviceStatus = healthCheckRegistry.runAllChecks();
		boolean isSystemHealthy = serviceStatus.isHealthy();
		if (isSystemHealthy) {
			return Response.ok().entity(serviceStatus).build();
		} else {
			return Response.status(Response.Status.SERVICE_UNAVAILABLE).entity(serviceStatus).build();
		}
	}

	/**
	 * Runs the health checks that simply identify  whether the application is running.
	 *
	 * Despite being useful for validating the state of the application, some health checks (logging initialized or not)
	 * aren't necessary to identify if the service has been properly deployed.
	 *
	 * @return Returns an HTTP Status code 200, if all health checks are ok, 503 if any has failed
	 */
	@GET
	@Produces(MediaType.APPLICATION_JSON)
	@Path(READY_PATH)
	public Response isApplicationRunning() {

		final HealthCheckStatus serviceStatus =
				healthCheckRegistry.runChecksDifferentFrom(Arrays.asList(HealthCheckValidationType.LOGGING_INITIALIZED));

		boolean isSystemHealthy = serviceStatus.isHealthy();
		if (isSystemHealthy) {
			return Response.ok().entity(serviceStatus).build();
		} else {
			return Response.status(Response.Status.SERVICE_UNAVAILABLE).entity(serviceStatus).build();
		}
	}
}
