/*
 * Copyright Java Operator SDK Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.javaoperatorsdk.operator.config.loader.provider;

import java.util.List;
import java.util.Properties;

import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.assertThat;

class PriorityListConfigProviderTest {

  private static PropertiesConfigProvider propsProvider(String key, String value) {
    Properties props = new Properties();
    if (key != null) {
      props.setProperty(key, value);
    }
    return new PropertiesConfigProvider(props);
  }

  @Test
  void returnsEmptyWhenAllProvidersReturnEmpty() {
    var provider =
        new AggregatePriorityListConfigProvider(
            List.of(new EnvVarConfigProvider(k -> null), propsProvider(null, null)));
    assertThat(provider.getValue("josdk.no.such.key", String.class)).isEmpty();
  }

  @Test
  void firstProviderWins() {
    var provider =
        new AggregatePriorityListConfigProvider(
            List.of(
                new EnvVarConfigProvider(k -> k.equals("JOSDK_TEST_KEY") ? "first" : null),
                propsProvider("josdk.test.key", "second")));
    assertThat(provider.getValue("josdk.test.key", String.class)).hasValue("first");
  }

  @Test
  void fallsBackToLaterProviderWhenEarlierReturnsEmpty() {
    var provider =
        new AggregatePriorityListConfigProvider(
            List.of(
                new EnvVarConfigProvider(k -> null),
                propsProvider("josdk.test.key", "from-second")));
    assertThat(provider.getValue("josdk.test.key", String.class)).hasValue("from-second");
  }

  @Test
  void respectsOrderWithThreeProviders() {
    var first = new EnvVarConfigProvider(k -> null);
    var second = propsProvider("josdk.test.key", "from-second");
    var third = new EnvVarConfigProvider(k -> k.equals("JOSDK_TEST_KEY") ? "from-third" : null);

    var provider = new AggregatePriorityListConfigProvider(List.of(first, second, third));
    assertThat(provider.getValue("josdk.test.key", String.class)).hasValue("from-second");
  }
}
