package fr.titionfire.ffsaf.rest;

import fr.titionfire.ffsaf.domain.service.WebhookService;
import fr.titionfire.ffsaf.rest.client.dto.HelloassoNotification;
import io.smallrye.mutiny.Uni;
import io.vertx.ext.web.RoutingContext;
import jakarta.inject.Inject;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import org.eclipse.microprofile.config.inject.ConfigProperty;
import org.eclipse.microprofile.openapi.annotations.Operation;
import org.jboss.logging.Logger;

@Path("api/webhook")
public class WebhookEndpoints {
    private static final Logger LOGGER = Logger.getLogger(WebhookEndpoints.class);

    @Inject
    WebhookService webhookService;

    @Inject
    RoutingContext context;

    @ConfigProperty(name = "helloasso.webhook.ip-source")
    String helloassoIp;

    @ConfigProperty(name = "quarkus.http.proxy.proxy-address-forwarding")
    boolean proxyForwarding;

    @POST
    @Path("ha")
    @Operation(hidden = true)
    @Consumes(MediaType.APPLICATION_JSON)
    public Uni<Response> helloAsso(HelloassoNotification notification) {
        String ip;
        if (proxyForwarding) {
            ip = context.request().getHeader("X-Forwarded-For");
            if (ip == null)
                ip = context.request().authority().host();
        } else {
            ip = context.request().authority().host();
        }

        if (!helloassoIp.equals(ip)) {
            LOGGER.infof("helloAsso webhook reject : bas ip (%s)", ip);
            return Uni.createFrom().item(Response.status(Response.Status.FORBIDDEN).build());
        }
        return webhookService.helloAssoNotification(notification);
    }
}
