/*
 * 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.baseapi.labelselector;

import java.time.Duration;
import java.util.Collections;
import java.util.Map;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

import io.fabric8.kubernetes.api.model.ObjectMetaBuilder;
import io.javaoperatorsdk.annotation.Sample;
import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension;

import static io.javaoperatorsdk.operator.baseapi.labelselector.LabelSelectorTestReconciler.LABEL_KEY;
import static io.javaoperatorsdk.operator.baseapi.labelselector.LabelSelectorTestReconciler.LABEL_VALUE;
import static org.assertj.core.api.Assertions.assertThat;
import static org.awaitility.Awaitility.await;

@Sample(
    tldr = "Label Selector for Custom Resource Filtering",
    description =
        """
        Demonstrates how to configure label selectors to filter which custom resources an \
        operator watches. The test verifies that only resources with matching labels trigger \
        reconciliation. This allows operators to selectively manage a subset of custom resources \
        based on their labels.
        """)
class LabelSelectorIT {

  @RegisterExtension
  LocallyRunOperatorExtension operator =
      LocallyRunOperatorExtension.builder()
          .withReconciler(new LabelSelectorTestReconciler())
          .build();

  @Test
  void filtersCustomResourceByLabel() {
    operator.create(resource("r1", true));
    operator.create(resource("r2", false));

    await()
        .pollDelay(Duration.ofMillis(150))
        .untilAsserted(
            () -> {
              assertThat(
                      operator
                          .getReconcilerOfType(LabelSelectorTestReconciler.class)
                          .getNumberOfExecutions())
                  .isEqualTo(1);
            });
  }

  LabelSelectorTestCustomResource resource(String name, boolean addLabel) {
    var res = new LabelSelectorTestCustomResource();
    res.setMetadata(
        new ObjectMetaBuilder()
            .withName(name)
            .withLabels(addLabel ? Map.of(LABEL_KEY, LABEL_VALUE) : Collections.emptyMap())
            .build());
    return res;
  }
}
