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

import ch.ergon.restal.jsonapi.document.data.ResourceObject;
import com.airlock.iam.factor.domain.model.fido.FidoAuthenticatorUnverifiedAssertionResponse;
import com.airlock.iam.factor.domain.model.fido.FidoClientFailure;
import com.airlock.iam.factor.domain.model.fido.FidoClientFailure.FidoClientFailureReason;
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.fido.FidoCheck;
import com.airlock.iam.flow.shared.infrastructure.transfer.request.fido.FidoAuthenticationPublicKeyCredentialRequest;
import com.airlock.iam.flow.shared.infrastructure.transfer.request.fido.FidoClientFailureRequest;
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.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;

@Path("/transaction-approval/fido")
public class FidoTransactionApprovalFlowResource {
   private final FlowResultMapper mapper;
   private final Provider<FidoCheck> fidoAuthentication;

   @Inject
   public FidoTransactionApprovalFlowResource(FlowResultMapper mapper, Provider<FidoCheck> fidoAuthentication) {
      this.mapper = mapper;
      this.fidoAuthentication = fidoAuthentication;
   }

   @ApiResponses(
      {
            @ApiResponse(
               responseCode = "200",
               description = "Transaction approval successful or further steps required.",
               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 = "The request was invalid.",
               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>FIDO_APPROVAL_FAILED</td>\n<td>The response of the FIDO authenticator to the previously obtained challenge could not be successfully verified.\nAs a result, the transaction approval has failed and the flow has been terminated. No retries are possible.</td>\n</tr>\n<tr>\n<td>FIDO_APPROVAL_TIMEOUT</td>\n<td>The response of the FIDO authenticator has timed out.</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"))
               }
            )
      }
   )
   @Operation(
      description = "Verify the FIDO authenticator's response.\n<p>The FIDO authenticator's response to the challenge (obtained previously as <a href=\"#additionalTransactionApprovalAttributes\">additional attribute</a>\nwith the <tt>FIDO_APPROVAL_ASSERTION_RESPONSE_REQUIRED</tt> next step code) contains information about the FIDO credential\nused for this transaction approval attempt as well as metadata that will be verified by IAM.</p>\n<p>This endpoint cannot verify or guarantee that the user has seen the transaction approval message sent with the challenge.\nThe FIDO/WebAuthn standard does currently not offer WYSIWYS (What you see is what you sign).</p>\n<div class=\"iam-resource-return\">Whether the check was successful. If the attribute <tt>nextStep</tt> is present in the response,\n further steps are required.</div>",
      tags = "FIDO",
      summary = "Verify response"
   )
   @POST
   @Path("/assertion-response/check")
   @Consumes("application/json")
   @Produces({"application/vnd.api+json", "application/json;qs=0.9"})
   public Response verify(
      @Parameter(description = "Contains the FIDO authenticator's response to the previously obtained challenge.") @NotNull @Valid FidoAuthenticationPublicKeyCredentialRequest request
   ) {
      FlowResult result = ((FidoCheck)this.fidoAuthentication.get())
         .verify(
            FidoAuthenticatorUnverifiedAssertionResponse.builder()
               .publicKeyCredentialId(request.getPublicKeyCredential().getId())
               .authenticatorData(request.getPublicKeyCredential().getResponse().getAuthenticatorData())
               .signature(request.getPublicKeyCredential().getResponse().getSignature())
               .userHandle(request.getPublicKeyCredential().getResponse().getUserHandle())
               .clientDataJson(request.getPublicKeyCredential().getResponse().getClientDataJSON())
               .build()
         );
      return this.mapper.toResponse(result, new ResourceObject[0]);
   }

   @ApiResponses(
      {
            @ApiResponse(
               responseCode = "200",
               description = "Transaction approval successful or further steps required. This is only possible if \"On Failure Gotos\" are configured on the step.",
               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 = "The request was invalid.",
               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>FIDO_APPROVAL_ABORTED</td>\n\t<td>The FIDO transaction approval has been aborted in the client. Returned if the <tt>reason</tt> in the request was \"ABORTED\".</td>\n</tr>\n<tr>\n\t<td>FIDO_APPROVAL_NOT_ALLOWED</td>\n\t<td>FIDO transaction approval was not allowed in the client. Returned if the <tt>reason</tt> in the request was \"NOT_ALLOWED\".</td>\n</tr>\n<tr>\n\t<td>FIDO_WEB_AUTHN_NOT_AVAILABLE</td>\n\t<td>The browser/client does not support WebAuthn/FIDO. Returned if the <tt>reason</tt> in the request was \"NO_WEB_AUTHN\".</td>\n</tr>\n<tr>\n\t<td>FIDO_APPROVAL_FAILED</td>\n\t<td>Returned if any other error occurred in the client. Returned if the <tt>reason</tt> in the request was \"UNKNOWN\".</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"))
               }
            )
      }
   )
   @Operation(
      description = "Report a FIDO client failure.<p>Allows the client to report a FIDO failure, resulting in a step failure.</p>\n<div class=\"iam-resource-return\">The status of the flow. If the attribute <tt>nextStep</tt> is present in the response,\n further steps are required to successfully complete the flow.</div>",
      tags = "FIDO",
      summary = "Report FIDO failure"
   )
   @POST
   @Path("/failure/report")
   @Consumes("application/json")
   @Produces({"application/vnd.api+json", "application/json;qs=0.9"})
   public Response handleClientFailure(
      @Parameter(description = "Contains information (name and message) describing the failure.") @Valid @NotNull FidoClientFailureRequest request
   ) {
      FidoClientFailure failure = new FidoClientFailure(FidoClientFailureReason.valueOf(request.getReason().name()), request.getMessage());
      return this.mapper.toResponse(((FidoCheck)this.fidoAuthentication.get()).reportClientFailure(failure), new ResourceObject[0]);
   }
}
