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

import com.airlock.iam.base.api.domain.model.exception.FailureException;
import com.airlock.iam.base.api.domain.model.plugin.LogicForConfig;
import com.airlock.iam.base.misc.date.Dates;
import com.airlock.iam.common.api.domain.model.valueprovider.ValueProvider;
import com.airlock.iam.common.domain.model.valueprovider.EntryFromMapValueProviderSettings;
import com.airlock.iam.elog.api.ELogger;
import com.airlock.iam.elog.api.ELoggerFactory;
import com.airlock.iam.flow.shared.application.configuration.valueprovider.DateFromMapValueProviderConfig;
import jakarta.inject.Inject;
import jakarta.inject.Provider;
import java.time.LocalDate;

@LogicForConfig(DateFromMapValueProviderConfig.class)
public class DateFromMapValueProvider extends EntryFromMapValueProvider implements ValueProvider<LocalDate> {
   private static final ELogger LOG = ELoggerFactory.getLogger(DateFromMapValueProvider.class);

   @Inject
   public DateFromMapValueProvider(Provider<ValueMapProviderList> valueMapProviderList, Provider<EntryFromMapValueProviderSettings> settings) {
      super(valueMapProviderList, settings);
   }

   public LocalDate getValue() {
      Object unidentified = this.getValueMapEntry();

      return switch (unidentified) {
         case null -> null;
         case LocalDate localDate -> localDate;
         case String str -> this.parseDateString(str);
         default -> throw new FailureException(
            "Cannot convert value with key '" + this.getEntryKey() + "' to a valid date. Actual type: " + unidentified.getClass().getSimpleName()
         );
      };
   }

   private LocalDate parseDateString(String str) {
      if (!Dates.isValidLocalDate(str)) {
         LOG.debug("String with key '" + this.getEntryKey() + "' is not a valid date format. Provided value: " + str);
         throw new FailureException("String with key '" + this.getEntryKey() + "' is not a valid date format.");
      } else {
         return Dates.toLocalDate(str);
      }
   }
}
