package com.airlock.iam.transactionapproval.health.infrastructure.resource;

import com.airlock.iam.common.infrastructure.transfer.documentation.response.HealthCheckWireFormatData;
import com.airlock.iam.elog.api.EDefaultLogType;
import com.airlock.iam.elog.api.ELogger;
import com.airlock.iam.elog.api.ELoggerFactory;
import com.airlock.iam.health.infrastructure.HealthCheckWireFormat;
import com.airlock.iam.health.infrastructure.service.ModuleReadinessService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.extensions.Extension;
import io.swagger.v3.oas.annotations.extensions.ExtensionProperty;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import jakarta.inject.Inject;
import jakarta.inject.Provider;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.Response;
import java.io.IOException;

@Path("/ready")
public final class TransactionApprovalReadinessResource {
   private static final ELogger LOG = ELoggerFactory.getLogger(TransactionApprovalReadinessResource.class);
   private final Provider<ModuleReadinessService> service;

   @Inject
   public TransactionApprovalReadinessResource(Provider<ModuleReadinessService> service) {
      this.service = service;
   }

   @ApiResponses(
      {
            @ApiResponse(
               responseCode = "200",
               description = "Readiness checks successfully executed.",
               content = @Content(mediaType = "application/json", schema = @Schema(implementation = HealthCheckWireFormatData.class))
            ),
            @ApiResponse(responseCode = "500", description = "Unexpected error while checking readiness.")
      }
   )
   @GET
   @Operation(
      description = "Internal health check endpoint that reports the readiness status of the Transaction Approval module.\n<div class=\"iam-resource-return\">Whether the Transaction Approval readiness status is \"UP\" or \"DOWN\".</div>",
      extensions = @Extension(properties = @ExtensionProperty(name = "x-internal", value = "true")),
      summary = "Check readiness"
   )
   @Produces("application/json")
   public Response checkReadiness() {
      HealthCheckWireFormat result = ((ModuleReadinessService)this.service.get()).checkAll();

      try {
         return Response.ok().entity(result.toJson()).build();
      } catch (IOException e) {
         LOG.warn(EDefaultLogType.GENERIC_LOG_TYPE, "Failed to produce readiness check response", e);
         return Response.serverError().build();
      }
   }
}
