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

import ch.ergon.restal.jsonapi.document.data.ResourceObject;
import com.airlock.iam.base.api.domain.model.user.UserId;
import com.airlock.iam.common.api.domain.model.user.UserIdentity;
import com.airlock.iam.common.api.infrastructure.annotation.DisableResponseDelay;
import com.airlock.iam.common.domain.model.user.PrincipalInfo;
import com.airlock.iam.flow.api.domain.model.flow.FlowId;
import com.airlock.iam.flow.api.domain.model.flow.FlowResult;
import com.airlock.iam.flow.api.infrastructure.mapper.FlowResultMapper;
import com.airlock.iam.flow.application.service.GenericFlowSelectionService;
import com.airlock.iam.flow.shared.api.domain.model.session.UserSession;
import com.airlock.iam.log.api.helpdesk.HelpdeskLogger;
import com.airlock.iam.transactionapproval.api.infrastructure.generated.transfer.response.TransactionApprovalFlowResultDataResourceDocument;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
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.validation.constraints.Size;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.Response;
import java.util.Optional;

@Path("/transaction-approval")
public final class TransactionApprovalFlowResource {
   private final HelpdeskLogger helpdeskLogger;
   private final Provider<PrincipalInfo> principalInfo;
   private final Provider<UserSession> userSession;
   private final Provider<GenericFlowSelectionService> flowSelectionService;
   private final FlowResultMapper mapper;

   @Inject
   public TransactionApprovalFlowResource(
      HelpdeskLogger helpdeskLogger,
      Provider<PrincipalInfo> principalInfo,
      Provider<UserSession> userSession,
      Provider<GenericFlowSelectionService> flowSelectionService,
      FlowResultMapper mapper
   ) {
      this.helpdeskLogger = helpdeskLogger;
      this.principalInfo = principalInfo;
      this.userSession = userSession;
      this.flowSelectionService = flowSelectionService;
      this.mapper = mapper;
   }

   @ApiResponse(responseCode = "204", description = "Transaction Approval session successfully terminated.")
   @DELETE
   @Produces({"application/vnd.api+json", "application/json;qs=0.9"})
   @Path("/flow")
   @Operation(
      description = "Aborts the current transaction approval flow and terminates any session connected to it.\n<div class=\"iam-resource-return\">If the termination of the transaction approval was successful.</div>",
      tags = "Flow Control",
      summary = "Abort flow"
   )
   @DisableResponseDelay
   public Response abort() {
      Optional<UserId> userId = ((PrincipalInfo)this.principalInfo.get()).getKnownIdentity().map(UserIdentity::id);
      ((UserSession)this.userSession.get()).terminate();
      this.helpdeskLogger.log(userId.orElse(null), "Transaction approval flow aborted.");
      return Response.noContent().build();
   }

   @ApiResponses(
      {
            @ApiResponse(
               responseCode = "200",
               description = " Transaction approval flow selection successful.",
               content = {
                     @Content(
                        mediaType = "application/vnd.api+json",
                        schema = @Schema(implementation = TransactionApprovalFlowResultDataResourceDocument.class)
                     ),
                     @Content(mediaType = "application/json", schema = @Schema(implementation = TransactionApprovalFlowResultDataResourceDocument.class))
               }
            ),
            @ApiResponse(
               responseCode = "400",
               description = "<div class=\"iam-error-code\"><table>\n<tr>\n<td>UNEXPECTED_CALL</td>\n<td>Another transaction approval flow is already in progress.</td>\n</tr>\n</table>\n</div>\n",
               content = {
                     @Content(mediaType = "application/vnd.api+json", schema = @Schema(ref = "json-api.yaml#/components/schemas/ErrorDocumentResponse")),
                     @Content(mediaType = "application/json", schema = @Schema(ref = "json-api.yaml#/components/schemas/ErrorDocumentResponse"))
               }
            ),
            @ApiResponse(
               responseCode = "404",
               description = "No flow with the requested ID exists.",
               content = {
                     @Content(mediaType = "application/vnd.api+json", schema = @Schema(ref = "json-api.yaml#/components/schemas/ErrorDocumentResponse")),
                     @Content(mediaType = "application/json", schema = @Schema(ref = "json-api.yaml#/components/schemas/ErrorDocumentResponse"))
               }
            )
      }
   )
   @Operation(
      description = "<div id=\"flowStart\"/>\nSelects a transaction approval flow.\n<div class=\"iam-resource-return\">A success response with a next step indicating the required next action.</div>",
      tags = "Flow Control",
      summary = "Select flow"
   )
   @POST
   @Path("/flows/{flowId}/select")
   @Produces({"application/vnd.api+json", "application/json;qs=0.9"})
   @DisableResponseDelay
   public Response selectFlow(
      @Parameter(description = "the ID of the selected flow as configured.") @PathParam("flowId") @Size(min = 1, max = 30) String flowId
   ) {
      GenericFlowSelectionService service = (GenericFlowSelectionService)this.flowSelectionService.get();
      FlowResult result = service.accessFlow(new FlowId(flowId));
      return this.mapper.toResponse(result, new ResourceObject[0]);
   }
}
