/*
 * RiskScape™ Copyright New Zealand Institute for Earth Science Limited
 * (Earth Sciences New Zealand) is distributed for research purposes only
 * under the terms of AGPLv3.
 *
 * RiskScape™ Copyright 2026 New Zealand Institute for Earth Science
 * Limited (Earth Sciences New Zealand). All rights reserved. Source code
 * available under the AGPLv3.
 * 
 * This program is free software: you can redistribute it and/or modify it under
 *  the terms of the GNU Affero General Public License as published by the Free
 *  Software Foundation, either version 3 of the License, or (at your option) any
 *  later version.
 * 
 * This program is distributed for RESEARCH PURPOSES ONLY, in the hope that it will
 * be useful for research and education initiatives.
 * 
 * If you are not a researcher, or you are a researcher who wishes to use this
 * program on terms other than AGPLv3 (including those who wish to restrict the
 * distribution of any source code created using this program), please contact:
 * https://riskscape.org.nz
 * 
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Affero General Public License for more details.  You should have received a copy
 * of the GNU Affero General Public License along with this program.  If not, see
 * <http://www.gnu.org/licenses/>.
 * 
 * By way of summary only, under the AGPLv3:
 *     • Permissions of this strongest copyleft license are conditioned
 *       on making available complete source code of licensed works and
 *       modifications, which include larger works using a licensed work,
 *       under the same license.
 *     • Copyright and license notices must be preserved.
 *     • Contributors provide an express grant of patent rights.
 *     • When a modified version is used to provide a service over a
 *       network, the complete source code of the modified version must be made
 *       available.
 */
package nz.org.riskscape.test;

import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;

import lombok.extern.slf4j.Slf4j;

/**
 * A {@link TestRule} that will retry a failed test three times before giving up.
 *
 * Useful for tests that are prone to flapping.
 *
 * Note that junit does not instantiate a new test class on a retry. It will reuse the existing class
 * and rerun any `@Before` annotated methods. This can cause problems if those methods are added things
 * to identified collections. So if you are using the retry rule then you should make sure that retries
 * won't fail due to re-adding items to identified collections.
 *
 * To ensure that test classes will pass tests on subsequent attempts set {@link #failUntilAttempt} to a
 * value greater than zero.
 */
@Slf4j
public class RetryRule implements TestRule {

  private static final int MAX_ATTEMPTS = 3;

  private final int failUntilAttempt;

  public RetryRule() {
    this(-1);
  }

  /**
   * Create a retry rule that will retry the test until failUntilAttempt.
   *
   * This allows you to confirm that the tests to be retried will pass on subsequent attempts.
   */
  public RetryRule(int failUntilAttempt) {
    this.failUntilAttempt = failUntilAttempt;
  }

  @Override
  public Statement apply(Statement base, Description description) {
    return new Statement() {
      @Override
      public void evaluate() throws Throwable {
        Throwable caughtThrowable = null;
        for (int i = 0; i < MAX_ATTEMPTS; i++) {
          try {
            base.evaluate();
            if (failUntilAttempt < 0 || i == failUntilAttempt) {
              return; // Test passed, no need to retry
            }
          } catch (Throwable t) {
            caughtThrowable = t;
            log.info("{} has failed on attempt {}.", description.getDisplayName(), i + 1);
          }
        }
        log.info("{} has failed {} times. Giving up.", description.getDisplayName(), MAX_ATTEMPTS);
        throw caughtThrowable; // Re-throw the last exception if all retries fail
      }
    };
  }

}
