package com.airlock.iam.oauth2.domain.service.consent;

import com.airlock.iam.common.api.domain.model.user.CurrentLocale;
import com.airlock.iam.core.misc.impl.authen.StringResourceProvider;
import com.airlock.iam.oauth2.api.domain.model.AuthorizationServerId;
import com.airlock.iam.oauth2.api.domain.model.OAuth2Scope;
import com.airlock.iam.oauth2.domain.model.provider.OAuth2ScopeAttribute;
import com.airlock.iam.oauth2.domain.service.OAuth2ScopeTranslationService;
import com.airlock.iam.oauth2.domain.service.ScopeTranslator;
import jakarta.inject.Inject;
import jakarta.inject.Provider;
import java.util.List;
import java.util.Map;
import java.util.Optional;

public class OAuth2ScopeTranslationServiceImpl implements OAuth2ScopeTranslationService {
   private final Provider<CurrentLocale> currentLocale;
   private final Provider<StringResourceProvider> stringResourceProvider;
   private final Provider<Map<AuthorizationServerId, ScopeTranslator>> scopeTranslators;

   @Inject
   public OAuth2ScopeTranslationServiceImpl(
      Provider<Map<AuthorizationServerId, ScopeTranslator>> scopeTranslators,
      Provider<CurrentLocale> currentLocale,
      Provider<StringResourceProvider> stringResourceProvider
   ) {
      this.scopeTranslators = scopeTranslators;
      this.currentLocale = currentLocale;
      this.stringResourceProvider = stringResourceProvider;
   }

   @Override
   public Optional<String> translateScope(AuthorizationServerId authorizationServerId, OAuth2Scope scope) {
      return this.translateScopeName(authorizationServerId, scope.name());
   }

   @Override
   public List<OAuth2ScopeAttribute> translateScopeNames(AuthorizationServerId authorizationServerId, List<OAuth2ScopeAttribute> attributes) {
      return attributes.stream()
         .map(
            attribute -> new OAuth2ScopeAttribute(
               attribute.getScope(),
               this.translateScopeName(authorizationServerId, attribute.getScope()),
               attribute.getConsentStatus(),
               attribute.getUpdatedAt()
            )
         )
         .toList();
   }

   private Optional<String> translateScopeName(AuthorizationServerId authorizationServerId, String scopeName) {
      return ((ScopeTranslator)((Map)this.scopeTranslators.get()).get(authorizationServerId))
         .translate(scopeName)
         .flatMap(key -> ((StringResourceProvider)this.stringResourceProvider.get()).translateResourceKey(((CurrentLocale)this.currentLocale.get()).get(), key));
   }
}
