package com.ankurm.resilience.snippets;

import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import io.github.resilience4j.timelimiter.annotation.TimeLimiter;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClient;

import java.util.concurrent.CompletableFuture;

/**
 * Illustrative: TimeLimiter + CircuitBreaker around a blocking RestClient call, made async so
 * the TimeLimiter has a future to stop waiting for. The companion repo's TESTED version of this
 * pattern is R4jTimeLimiterService.guardedLookup.
 *
 * Caveat: the TimeLimiter stops WAITING after timeoutDuration; with a plain blocking HTTP call
 * the request itself keeps running unless the client has its own read timeout. Set both.
 */
@Service
public class PaymentAsyncClient {

    private final RestClient restClient;

    public PaymentAsyncClient(RestClient.Builder builder) {
        this.restClient = builder.baseUrl("http://payments.internal").build();
    }

    @CircuitBreaker(name = "paymentService", fallbackMethod = "paymentFallback")
    @TimeLimiter(name = "paymentService")
    public CompletableFuture<String> processPaymentAsync(String orderId) {
        return CompletableFuture.supplyAsync(() ->
                restClient.get().uri("/pay/{id}", orderId).retrieve().body(String.class));
    }

    private CompletableFuture<String> paymentFallback(String orderId, Throwable ex) {
        return CompletableFuture.completedFuture("PAYMENT_UNAVAILABLE:" + orderId);
    }
}
