package fr.titionfire.ffsaf.rest.client;

import fr.titionfire.ffsaf.rest.client.dto.CheckoutIntentsRequest;
import fr.titionfire.ffsaf.rest.client.dto.CheckoutIntentsResponse;
import io.quarkus.rest.client.reactive.ClientExceptionMapper;
import io.smallrye.mutiny.Uni;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import org.eclipse.microprofile.rest.client.annotation.RegisterClientHeaders;
import org.eclipse.microprofile.rest.client.inject.RegisterRestClient;

import java.io.ByteArrayInputStream;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;

@Path("/")
@RegisterRestClient(configKey = "helloasso-api")
@RegisterClientHeaders(HelloAssoHeadersFactory.class)
public interface HelloAssoService {

    @GET
    @Path("/users/me/organizations")
    @Produces("text/plain")
    Uni<String> test();

    @POST
    @Path("organizations/{organizationSlug}/checkout-intents")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    Uni<CheckoutIntentsResponse> checkout(@PathParam("organizationSlug") String organizationSlug,
                                          CheckoutIntentsRequest data);

    @ClientExceptionMapper
    static RuntimeException toException(Response response, Method method) {
        if (!method.getDeclaringClass().getName().equals("fr.titionfire.ffsaf.rest.client.HelloAssoService"))
            return null;

        if (method.getName().equals("checkout")) {
            if (response.getStatus() == 400) {
                if (response.getEntity() instanceof ByteArrayInputStream) {
                    ByteArrayInputStream error = response.readEntity(ByteArrayInputStream.class);
                    return new RuntimeException(new String(error.readAllBytes(), StandardCharsets.UTF_8));
                }

                return new RuntimeException("The remote service responded with HTTP 400");
            }
        }
        return null;
    }
}