package com.airlock.iam.flow.shared.domain.model.otp;

import com.airlock.iam.common.api.domain.model.user.UserIdentity;
import com.airlock.iam.common.domain.model.user.PrincipalInfo;
import com.airlock.iam.core.misc.authen.result.AuthenticationFailedToken;
import com.airlock.iam.core.misc.authen.result.AuthenticationResult;
import com.airlock.iam.elog.api.ELogger;
import com.airlock.iam.elog.api.ELoggerFactory;
import com.airlock.iam.log.api.helpdesk.HelpdeskLogger;
import jakarta.inject.Inject;

public final class OtpCheckingResultLogger {
   private static final ELogger LOG = ELoggerFactory.getLogger(OtpCheckingResultLogger.class);
   private final PrincipalInfo principalInfo;
   private final HelpdeskLogger logger;

   @Inject
   public OtpCheckingResultLogger(PrincipalInfo principalInfo, HelpdeskLogger signingLogger) {
      this.principalInfo = principalInfo;
      this.logger = signingLogger;
   }

   public void log(AuthenticationResult authenticationResult) {
      LOG.debug("Result from authenticator: " + authenticationResult);
      if (authenticationResult.authenticationSucceeded()) {
         this.logToUserTrail("OTP verification successful.");
      } else if (authenticationResult.isOfType(AuthenticationFailedToken.TOKEN_WRONG)) {
         this.logToUserTrail("OTP verification failed: OTP incorrect.");
      } else if (authenticationResult.isOfType(AuthenticationFailedToken.NEXT_TOKEN_REQUIRED)) {
         this.logToUserTrail("OTP verification failed: OTP incorrect, retry.");
      } else if (authenticationResult.isOfType(AuthenticationFailedToken.TOKEN_EXPIRED)) {
         this.logToUserTrail("OTP verification failed: OTP expired.");
      }
   }

   private void logToUserTrail(String message) {
      this.logger.log(this.principalInfo.getKnownIdentity().map(UserIdentity::id).orElseThrow(), message);
   }
}
