package com.airlock.iam.oauth2.domain.model.token.revocation;

import com.airlock.iam.base.api.domain.model.exception.FailureException;
import com.airlock.iam.common.api.domain.model.persistency.exception.PersisterException;
import com.airlock.iam.oauth2.api.domain.model.OAuth2ClientId;
import com.airlock.iam.oauth2.domain.model.token.OAuth2AccessToken;
import com.airlock.iam.oauth2.domain.model.token.OAuth2RefreshToken;
import com.airlock.iam.oauth2.domain.model.token.OAuth2Token;
import com.airlock.iam.oauth2.domain.service.persistence.OAuth2TokenUpdater;
import com.airlock.iam.oauth2.domain.service.token.OAuth2LoginTokenService;
import com.airlock.iam.oauth2.domain.service.token.TokenRevocationTokenManager;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.util.Optional;
import lombok.NonNull;

public final class OAuth2TokenRevocationTokenManager implements TokenRevocationTokenManager {
   @NonNull
   private final OAuth2LoginTokenService tokenService;
   @NonNull
   private final OAuth2TokenUpdater tokenUpdater;

   @Override
   public Optional<OAuth2AccessToken> getAccessTokenWithoutInvalidation(String tokenValue, OAuth2ClientId clientId) {
      try {
         return this.tokenService.getAccessTokenWithoutInvalidation(tokenValue, Optional.of(clientId));
      } catch (PersisterException e) {
         throw new FailureException("Error getting access token: " + e.getMessage(), e);
      }
   }

   @Override
   public Optional<OAuth2RefreshToken> getRefreshToken(String tokenValue, OAuth2ClientId clientId) {
      try {
         return this.tokenService.getRefreshTokenWithoutInvalidation(tokenValue, clientId);
      } catch (PersisterException e) {
         throw new FailureException("Error getting refresh token: " + e.getMessage(), e);
      }
   }

   @Override
   public void invalidate(OAuth2Token token) {
      this.tokenUpdater.invalidate(token);
   }

   @SuppressFBWarnings(justification = "generated code")
   public OAuth2TokenRevocationTokenManager(@NonNull OAuth2LoginTokenService tokenService, @NonNull OAuth2TokenUpdater tokenUpdater) {
      if (tokenService == null) {
         throw new NullPointerException("tokenService is marked non-null but is null");
      }

      if (tokenUpdater == null) {
         throw new NullPointerException("tokenUpdater is marked non-null but is null");
      }

      this.tokenService = tokenService;
      this.tokenUpdater = tokenUpdater;
   }
}
