package cz.moneta.test.harness.connectors.wso2;

import cz.moneta.test.harness.connectors.rest.ResponseHandler;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.http.HttpStatus;

import jakarta.ws.rs.client.Invocation;
import jakarta.ws.rs.core.Response;
import java.util.function.Function;
import java.util.function.Supplier;

public class TokenRenewalResponseHandler implements ResponseHandler<Pair<Invocation.Builder, Function<Invocation.Builder, Response>>, Response> {

    private final Supplier<String> tokenSupplier;

    public TokenRenewalResponseHandler(Supplier<String> tokenSupplier) {
        this.tokenSupplier = tokenSupplier;
    }

    /**
     * Checks whether the HTTP response status is 401 UNAUTHORIZED in which case it resends the original request with
     * a renewed Authorization Bearer token
     */
    @Override
    public Response handle(Pair<Invocation.Builder, Function<Invocation.Builder, Response>> invocation, Response response) {
        if (response.getStatus() == HttpStatus.SC_UNAUTHORIZED) {
            Invocation.Builder builder = invocation.getLeft().header("Authorization", "Bearer " + tokenSupplier.get());
            return invocation.getRight().apply(builder);
        } else {
            return response;
        }
    }
}
