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

import ch.ergon.restal.jsonapi.document.data.ResourceObject;
import com.airlock.iam.common.api.domain.model.otp.UnverifiedOtp;
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.otp.EmailOtpAuthentication;
import com.airlock.iam.flow.shared.infrastructure.transfer.request.GenericOtpCheckRequest;
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/email/otp")
public class EmailOtpTransactionApprovalFlowResource {
   private final FlowResultMapper mapper;
   private final Provider<EmailOtpAuthentication> emailOtpAuthentication;

   @Inject
   public EmailOtpTransactionApprovalFlowResource(FlowResultMapper mapper, Provider<EmailOtpAuthentication> emailOtpAuthentication) {
      this.mapper = mapper;
      this.emailOtpAuthentication = emailOtpAuthentication;
   }

   @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 = "<div class=\"iam-error-code\"><table>\n<tr>\n<td>OTP_WRONG</td>\n<td>The OTP could not be validated successfully.</td>\n</tr>\n</table>\n</div>\n<br>Possible next step: <tt>EMAIL_OTP_CHECK_REQUIRED</tt> (as documented <a href=\"#nextApprovalStepCodes\">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>OTP_WRONG</td>\n<td>The OTP could not be validated successfully. No retries are possible.</td>\n</tr>\n<tr>\n<td>OTP_EXPIRED</td>\n<td>The OTP has expired.</td>\n</tr>\n</table>\n</div>\n<br>The current transaction approval 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"))
               }
            )
      }
   )
   @POST
   @Path("/check")
   @Consumes("application/json")
   @Produces({"application/vnd.api+json", "application/json;qs=0.9"})
   @Operation(
      description = "Checks the submitted email OTP.\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 to successfully approve the transaction. If the attribute is missing, the transaction approval\n of the user was successful.</div>",
      tags = "Email OTP",
      summary = "Check email OTP"
   )
   public Response checkOtp(@Parameter(description = "Request containing the OTP.") @NotNull @Valid GenericOtpCheckRequest request) {
      FlowResult result = ((EmailOtpAuthentication)this.emailOtpAuthentication.get()).checkOtp(UnverifiedOtp.unverifiedOtp(request.getOtp()));
      return this.mapper.toResponse(result, new ResourceObject[0]);
   }

   @ApiResponses(
      {
            @ApiResponse(
               responseCode = "200",
               description = "The OTP has been resent.",
               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>EMAIL_OTP_RESEND_REFUSED</td>\n<td>The OTP could not be resent.</td>\n</tr>\n</table>\n</div>\n<br>Possible next step: <tt>EMAIL_OTP_CHECK_REQUIRED</tt> (as documented <a href=\"#nextApprovalStepCodes\">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 = "Resend failed. The current transaction approval flow has been aborted.",
               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"))
               }
            )
      }
   )
   @POST
   @Produces({"application/vnd.api+json", "application/json;qs=0.9"})
   @Path("/resend")
   @Operation(
      description = "Resends the email OTP.\n<div class=\"iam-resource-return\">Whether the resend was successful and informs about the <tt>nextStep</tt>.\n Additionally, the response includes information about the possibility of an OTP resend.</div>",
      tags = "Email OTP",
      summary = "Resend email OTP"
   )
   public Response resendOtp() {
      FlowResult resendResult = ((EmailOtpAuthentication)this.emailOtpAuthentication.get()).resend();
      return this.mapper.toResponse(resendResult, new ResourceObject[0]);
   }
}
