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

import ch.ergon.restal.jsonapi.document.data.ResourceObject;
import com.airlock.iam.flow.api.domain.model.flow.Flow;
import com.airlock.iam.flow.api.domain.model.flow.FlowResult;
import com.airlock.iam.flow.api.infrastructure.mapper.FlowResultMapper;
import com.airlock.iam.flow.shared.domain.model.step.acknowledgemessage.AcknowledgeMessageStep;
import com.airlock.iam.transactionapproval.api.infrastructure.generated.transfer.response.TransactionApprovalFlowResultDataResourceDocument;
import io.swagger.v3.oas.annotations.Operation;
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 jakarta.inject.Inject;
import jakarta.inject.Provider;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.Response;

@Path("/transaction-approval/message")
public class TransactionApprovalMessageAcknowledgeFlowResource {
   private final Provider<Flow> flow;
   private final FlowResultMapper mapper;

   @Inject
   public TransactionApprovalMessageAcknowledgeFlowResource(Provider<Flow> flow, FlowResultMapper mapper) {
      this.flow = flow;
      this.mapper = mapper;
   }

   @ApiResponse(
      responseCode = "200",
      description = "Message successfully acknowledged or further steps required (as documented <a href=\"#nextApprovalStepCodes\">here</a>).",
      content = {
            @Content(mediaType = "application/vnd.api+json", schema = @Schema(implementation = TransactionApprovalFlowResultDataResourceDocument.class)),
            @Content(mediaType = "application/json", schema = @Schema(implementation = TransactionApprovalFlowResultDataResourceDocument.class))
      }
   )
   @POST
   @Path("/acknowledge")
   @Produces({"application/vnd.api+json", "application/json;qs=0.9"})
   @Operation(
      description = "Acknowledges a previously received message.\nThe message can be a pre-configured message ID or server-generated message, depending on the step configuration.\nIt has been received as an additional in a previous step response (as documented <a href=\"#additionalTransactionApprovalAttributes\">here</a>).\n<div class=\"iam-resource-return\">If the attribute <tt>nextStep</tt> is present in the response,\n further steps are required to successfully continue with the flow. If the attribute is missing,\n the transaction approval flow is successfully terminated.</div>",
      tags = "Message Acknowledgement",
      summary = "Acknowledge message"
   )
   public Response acknowledgeMessageId() {
      FlowResult result = ((Flow)this.flow.get()).execute(AcknowledgeMessageStep::acknowledge, AcknowledgeMessageStep.class);
      return this.mapper.toResponse(result, new ResourceObject[0]);
   }
}
