package com.ankurm.resilience.snippets;

import io.github.resilience4j.retry.annotation.Retry;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClient;

/**
 * Illustrative, production-shaped Resilience4j @Retry around a RestClient call.
 * NOT executed against a real server in the companion repo (the repo's tested retry is
 * R4jRetryService). Pair it with this YAML:
 *
 * resilience4j:
 *   retry:
 *     instances:
 *       inventoryService:
 *         maxAttempts: 3
 *         waitDuration: 500ms
 *         enableExponentialBackoff: true
 *         exponentialBackoffMultiplier: 2
 *         retryExceptions:
 *           - java.io.IOException
 *         ignoreExceptions:
 *           - com.example.BusinessValidationException
 *
 * Only retry idempotent operations: a GET like this one is safe, a POST that timed out after the
 * server processed it is how duplicate payments happen.
 */
@Service
public class InventoryClient {

    private final RestClient restClient;

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

    @Retry(name = "inventoryService", fallbackMethod = "inventoryFallback")
    public String checkStock(String productId) {
        return restClient.get().uri("/stock/{id}", productId).retrieve().body(String.class);
    }

    private String inventoryFallback(String productId, Throwable ex) {
        return "Stock check failed after retries for " + productId;
    }
}
