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

import com.airlock.iam.common.api.domain.model.binary.ByteSequence;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.util.Base64;
import lombok.NonNull;
import org.apache.commons.lang3.Validate;

public final class FidoPublicKeyCredentialId implements FidoBinaryValue {
   private static final int MINIMAL_NUMBER_OF_BYTES = 16;
   private static final int MAXIMAL_NUMBER_OF_BYTES = 65535;
   private static final int NUMBER_OF_CHARACTERS_DISPLAYED = 50;
   @NonNull
   private final ByteSequence id;

   private FidoPublicKeyCredentialId(byte[] bytes) {
      Validate.inclusiveBetween(
         16L, 65535L, bytes.length, String.format("Invalid number of bytes. A FIDO public-key credential ID needs to have between %d and %d bytes", 16, 65535)
      );
      this.id = ByteSequence.byteSequence(bytes);
   }

   public static FidoPublicKeyCredentialId publicKeyCredentialId(byte[] bytes) {
      return new FidoPublicKeyCredentialId(bytes);
   }

   public static FidoPublicKeyCredentialId publicKeyCredentialId(@NonNull String base64UrlString) {
      if (base64UrlString == null) {
         throw new NullPointerException("base64UrlString is marked non-null but is null");
      } else {
         return new FidoPublicKeyCredentialId(Base64.getUrlDecoder().decode(base64UrlString));
      }
   }

   @Override
   public byte[] bytes() {
      return this.id.bytes();
   }

   public byte[] sha512() {
      return this.id.sha512().bytes();
   }

   public String base64Url() {
      return this.id.base64Url();
   }

   public String asTruncatedString() {
      return this.id.base64UrlTruncated(50);
   }

   @Override
   public String toString() {
      return this.asTruncatedString();
   }

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

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