package com.airlock.iam.oauth2.infrastructure.repository;

import com.github.benmanes.caffeine.cache.Expiry;
import java.net.URI;
import java.time.Duration;

public class RemoteAccessTokenExpiry implements Expiry<URI, AccessTokenCacheEntry> {
   private static final Duration MINIMAL_CACHE_EXPIRY = Duration.ofSeconds(5L);

   public long expireAfterCreate(URI key, AccessTokenCacheEntry token, long currentTime) {
      return determineExpiryTime(token);
   }

   public long expireAfterUpdate(URI key, AccessTokenCacheEntry token, long currentTime, long currentDuration) {
      return determineExpiryTime(token);
   }

   public long expireAfterRead(URI key, AccessTokenCacheEntry token, long currentTime, long currentDuration) {
      return currentDuration;
   }

   private static long determineExpiryTime(AccessTokenCacheEntry token) {
      if (token == null) {
         return 0L;
      }

      Duration expireAfterCreate = token.getExpiresIn().minus(MINIMAL_CACHE_EXPIRY);
      return expireAfterCreate.isNegative() ? 0L : expireAfterCreate.toNanos();
   }
}
