package eu.teraflow.automation;

import grpc.health.v1.HealthOuterClass;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import org.eclipse.microprofile.health.HealthCheck;
import org.eclipse.microprofile.health.HealthCheckResponse;
import org.eclipse.microprofile.health.HealthCheckResponseBuilder;
import org.eclipse.microprofile.health.Readiness;
import org.jboss.logging.Logger;

@Readiness
@ApplicationScoped
public class SimpleReadinessCheck implements HealthCheck {

    private static final Logger LOGGER = Logger.getLogger(SimpleReadinessCheck.class);
    private final ContextHealthCheck healthCheck;

    @Inject
    public SimpleReadinessCheck(ContextHealthCheck healthCheck) {
        this.healthCheck = healthCheck;
    }

    @Override
    public HealthCheckResponse call() {

        HealthCheckResponseBuilder responseBuilder =
                HealthCheckResponse.named("Context service health check");

        try {
            checkContextServiceConnection();
            responseBuilder.up();
        } catch (IllegalStateException e) {
            responseBuilder.down();
        }

        return responseBuilder.build();
    }

    private void checkContextServiceConnection() {

        final var healthCheckResponseUni = healthCheck.getServingStatus();

        healthCheckResponseUni
                .subscribe()
                .with(
                        healthCheckResponse -> {
                            final var status = healthCheckResponse.getStatus().toString();
                            LOGGER.infof("HEALTH STATUS is: %s", status);
                            final var expectedStatus =
                                    HealthOuterClass.HealthCheckResponse.ServingStatus.SERVING.toString();

                            if (!status.equals(expectedStatus)) {
                                throw new IllegalStateException("Cannot contact context service");
                            }
                        });
    }
}
