package com.airlock.iam.authentication.domain.model.fido;

import com.airlock.iam.base.api.domain.model.exception.FailureException;
import com.airlock.iam.base.api.domain.model.mapification.MapifiedValues;
import com.airlock.iam.base.domain.model.mapification.MapifiedValuesBuilder;
import com.airlock.iam.factor.domain.model.fido.FidoPublicKeyCredentialRequestOptions;
import com.airlock.iam.flow.api.domain.model.step.StepSession;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.util.Optional;
import org.apache.commons.lang3.Validate;

public final class FidoPasswordlessAuthenticationStepSession implements FidoChallengeSession, StepSession {
   private static final String OPTIONS_KEY = "options";
   private Optional<FidoPublicKeyCredentialRequestOptions> challenge = Optional.empty();

   static FidoPasswordlessAuthenticationStepSession emptySession() {
      return new FidoPasswordlessAuthenticationStepSession();
   }

   @Override
   public FidoPublicKeyCredentialRequestOptions getChallenge() {
      return this.challenge.orElseThrow(() -> new FailureException("Challenge should have been initialized"));
   }

   @Override
   public void saveChallenge(FidoPublicKeyCredentialRequestOptions options) {
      Validate.isTrue(this.challenge.isEmpty(), "challenge can only be set once", new Object[0]);
      this.challenge = Optional.of(options);
   }

   @Override
   public MapifiedValues mapify() {
      return MapifiedValuesBuilder.mapifiedValues().putIfPresent("options", this.challenge.map(FidoPublicKeyCredentialRequestOptions::mapify)).build();
   }

   public static FidoPasswordlessAuthenticationStepSession demapify(MapifiedValues values) {
      return new FidoPasswordlessAuthenticationStepSession(values.demapifyOptional("options", FidoPublicKeyCredentialRequestOptions::demapify));
   }

   @SuppressFBWarnings(justification = "generated code")
   private FidoPasswordlessAuthenticationStepSession() {
   }

   @SuppressFBWarnings(justification = "generated code")
   @Override
   public boolean equals(Object o) {
      if (o == this) {
         return true;
      } else if (!(o instanceof FidoPasswordlessAuthenticationStepSession other)) {
         return false;
      } else {
         Object this$challenge = this.challenge;
         Object other$challenge = other.challenge;
         return this$challenge == null ? other$challenge == null : this$challenge.equals(other$challenge);
      }
   }

   @SuppressFBWarnings(justification = "generated code")
   @Override
   public int hashCode() {
      int PRIME = 59;
      int result = 1;
      Object $challenge = this.challenge;
      return result * 59 + ($challenge == null ? 43 : $challenge.hashCode());
   }

   @SuppressFBWarnings(justification = "generated code")
   private FidoPasswordlessAuthenticationStepSession(Optional<FidoPublicKeyCredentialRequestOptions> challenge) {
      this.challenge = challenge;
   }
}
