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

import com.airlock.iam.authentication.infrastructure.generated.transfer.response.MatrixChallengeDataResourceDocument;
import com.airlock.iam.authentication.infrastructure.transfer.response.MatrixChallengeData;
import com.airlock.iam.flow.api.domain.model.flow.FlowResult;
import com.airlock.iam.flow.api.infrastructure.mapper.FlowResultMapper;
import com.airlock.iam.flow.auth.api.infrastructure.generated.transfer.response.AuthenticationFlowResultDataResourceDocument;
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 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("/matrix")
public class MatrixAuthenticationFlowResource {
   private final FlowResultMapper resultMapper;
   private final Provider<MatrixCheck> matrixAuthentication;

   @Inject
   public MatrixAuthenticationFlowResource(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 = MatrixChallengeDataResourceDocument.class)),
            @Content(mediaType = "application/json", schema = @Schema(implementation = MatrixChallengeDataResourceDocument.class))
      }
   )
   @Deprecated
   @Operation(
      description = "> [!caution]\n> This endpoint is deprecated. The challenges are returned as\n<a href=\"#additionalAuthAttributes\">additional attribute</a> with the <tt>MATRIX_RESPONSE_REQUIRED</tt> next step code.\n<p>Returns one or more challenges for matrix/index list authentication.</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 this.resultMapper.toResponseWithData(result, MatrixChallengeData.class);
   }

   @ApiResponses(
      {
            @ApiResponse(
               responseCode = "200",
               description = "Authentication successful or further steps required.",
               content = {
                     @Content(mediaType = "application/vnd.api+json", schema = @Schema(implementation = AuthenticationFlowResultDataResourceDocument.class)),
                     @Content(mediaType = "application/json", schema = @Schema(implementation = AuthenticationFlowResultDataResourceDocument.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=\"#nextAuthStepCodes\">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 authentication 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.\n<div class=\"iam-resource-return\">Whether the check was successful. If the attribute <tt>nextAuthStep</tt> is present in the response,\n further steps are required to successfully authenticate. If the attribute is missing, the user is\n successfully authenticated.</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 checkChallengeResponse(@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 this.resultMapper.toResponse(result);
   }
}
