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

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.application.service.matrix.MatrixCheck;
import com.airlock.iam.flow.shared.domain.model.matrix.MatrixChallengeResponse;
import com.airlock.iam.flow.shared.infrastructure.transfer.request.MatrixChallengeCheckRequest;
import com.airlock.iam.publicselfservice.api.infrastructure.generated.transfer.response.PublicSelfServiceFlowResultDataResourceDocument;
import com.airlock.iam.publicselfservice.infrastructure.generated.transfer.PublicSelfServiceMatrixChallengeDataResourceDocument;
import com.airlock.iam.publicselfservice.infrastructure.transfer.PublicSelfServiceMatrixChallengeData;
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.Valid;
import jakarta.validation.constraints.NotNull;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;

@Path("/approval/matrix")
public final class PublicSelfServicMatrixApprovalResource {
   private final Provider<FlowResultMapper> resultMapper;
   private final Provider<MatrixCheck> matrixAuthentication;

   @Inject
   public PublicSelfServicMatrixApprovalResource(Provider<FlowResultMapper> resultMapper, Provider<MatrixCheck> matrixAuthentication) {
      this.resultMapper = resultMapper;
      this.matrixAuthentication = matrixAuthentication;
   }

   @ApiResponse(
      responseCode = "200",
      description = "The challenge has been returned.",
      content = {
            @Content(mediaType = "application/vnd.api+json", schema = @Schema(implementation = PublicSelfServiceMatrixChallengeDataResourceDocument.class)),
            @Content(mediaType = "application/json", schema = @Schema(implementation = PublicSelfServiceMatrixChallengeDataResourceDocument.class))
      }
   )
   @Deprecated
   @Operation(
      description = "> [!caution]\n> This endpoint is deprecated. The challenges are returned as\n<a href=\"#additionalPublicSelfServiceAttributes\">additional attribute</a> with the <tt>MATRIX_RESPONSE_REQUIRED</tt> next step code.\n<p>Returns one or more challenges for matrix/index list approval.</p>\n<div class=\"iam-resource-return\">A list of one or more matrix coordinates or index list indexes.</div>",
      tags = "Matrix Cards",
      summary = "Get challenges"
   )
   @POST
   @Produces({"application/vnd.api+json", "application/json;qs=0.9"})
   @Path("challenge/retrieve")
   public Response retrieveChallenge() {
      FlowResult result = ((MatrixCheck)this.matrixAuthentication.get()).getCurrentChallenge();
      return ((FlowResultMapper)this.resultMapper.get()).toResponseWithData(result, PublicSelfServiceMatrixChallengeData.class);
   }

   @ApiResponses(
      {
            @ApiResponse(
               responseCode = "200",
               description = "Challenge successfully verified.",
               content = {
                     @Content(mediaType = "application/vnd.api+json", schema = @Schema(implementation = PublicSelfServiceFlowResultDataResourceDocument.class)),
                     @Content(mediaType = "application/json", schema = @Schema(implementation = PublicSelfServiceFlowResultDataResourceDocument.class))
               }
            ),
            @ApiResponse(
               responseCode = "400",
               description = "<div class=\"iam-error-code\"><table>\n<tr>\n<td>MATRIX_RESPONSE_WRONG</td>\n<td>One or more responses could not be validated successfully. Retry again.<br>\nSince challenge coordinates may change after failed attempts (depending on configuration),\nthe new ones might have to be requested again.</td>\n</tr>\n</table>\n</div>\n<br>Possible next step: <tt>MATRIX_RESPONSE_REQUIRED</tt> (as documented <a href=\"#nextPublicSelfServiceStepCodes\">here</a>).\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 = "403",
               description = "<div class=\"iam-error-code\"><table>\n<tr>\n<td>MATRIX_RESPONSE_WRONG</td>\n<td>One or more responses could not be validated successfully.</td>\n</tr>\n<tr>\n<td>TOO_MANY_UNANSWERED_CHALLENGES</td>\n<td>Too many challenges were requested but not answered. Try again later.</td>\n</tr>\n</table>\n</div>\n<br>The current public self-service flow has been aborted.\n<br>Possible next step: none.\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"))
               }
            )
      }
   )
   @Operation(
      description = "Verifies the submitted challenge response. Note that unlike identity verification, approval REST calls require an existing user\nand cannot prevent username enumeration.\n<div class=\"iam-resource-return\">Whether the check was successful. Gives information about the next step required.</div>",
      tags = "Matrix Cards",
      summary = "Verify response"
   )
   @POST
   @Path("check")
   @Consumes("application/json")
   @Produces({"application/vnd.api+json", "application/json;qs=0.9"})
   public Response checkMtanOtp(@Parameter(description = "Contains the challenge response(s).") @NotNull @Valid MatrixChallengeCheckRequest request) {
      List<MatrixChallengeResponse> challengeResponses = new ArrayList<>();

      for (Entry<String, String> entry : request.getChallengeResponse().entrySet()) {
         challengeResponses.add(new MatrixChallengeResponse(entry.getKey(), entry.getValue()));
      }

      FlowResult result = ((MatrixCheck)this.matrixAuthentication.get()).checkChallengeResponse(challengeResponses);
      return ((FlowResultMapper)this.resultMapper.get()).toResponse(result);
   }
}
