package com.airlock.iam.publicselfservice.application.configuration.steps;

import com.airlock.iam.core.misc.impl.authen.mtan.TokenDataMtanHandler;
import com.airlock.iam.plugin.api.config.ConfigurationContext;
import com.airlock.iam.plugin.api.config.ConfigurationEnvironment;
import com.airlock.iam.plugin.api.config.PluginConfiguration;
import com.airlock.iam.plugin.api.exception.ConfigurationException;
import com.airlock.iam.plugin.api.exception.PropertyConfigurationException;
import com.airlock.iam.plugin.api.valuereader.IntegerPropertyValueReader;
import com.airlock.iam.plugin.api.valuereader.PluginPropertyValueReader;

public class SmsIdentityVerificationStepConfigValidator {
   private final PluginConfiguration config;
   private final ConfigurationContext context;
   private final ConfigurationEnvironment env;

   public SmsIdentityVerificationStepConfigValidator(PluginConfiguration config, ConfigurationContext context, ConfigurationEnvironment env) {
      this.config = config;
      this.context = context;
      this.env = env;
   }

   public void validate() throws ConfigurationException {
      PluginConfiguration basicSettingsPluginConfiguration = PluginPropertyValueReader.effectivePluginPropertyValue(
         this.config, "mtanSettings", this.env, this.context
      );
      if (basicSettingsPluginConfiguration != null) {
         PluginConfiguration mtanHandlerPluginConfiguration = PluginPropertyValueReader.effectivePluginPropertyValue(
            basicSettingsPluginConfiguration, "mtanHandler", this.env, this.context
         );
         if (mtanHandlerPluginConfiguration != null && mtanHandlerPluginConfiguration.isOfPluginClass(TokenDataMtanHandler.class)) {
            Integer maxTokenCount = IntegerPropertyValueReader.effectiveIntegerConfigValue(
               mtanHandlerPluginConfiguration, "maxTokenCount", this.env, this.context
            );
            if (maxTokenCount == null || maxTokenCount != 1) {
               throw new PropertyConfigurationException(
                  mtanHandlerPluginConfiguration,
                  this.env,
                  this.context,
                  "The property Max Token Count must be set to 1 if used in an SMS Identity Verification Step.",
                  new String[0]
               );
            }
         }
      }
   }
}
