package com.banesco.common.application.service;

import com.banesco.common.application.usecase.HttpClientUseCase;
import com.banesco.common.domain.model.HttpRequest;
import jakarta.ws.rs.core.MediaType;
import lombok.extern.slf4j.Slf4j;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import jakarta.ws.rs.client.Entity;
import jakarta.ws.rs.client.Invocation;
import jakarta.ws.rs.client.WebTarget;
import jakarta.ws.rs.core.Response;

import java.util.concurrent.TimeUnit;
import java.util.Map;

@Slf4j
@ApplicationScoped
public class HttpClientService implements HttpClientUseCase {

    @Override
    public <T> T execute(HttpRequest request) {
        String finalUrl = request.getUrl();

        if (request.getPathParams() != null && !request.getPathParams().isEmpty()) {
            log.debug("PathParams antes de reemplazar: {}", request.getPathParams());
            log.debug("URL original: {}", finalUrl);

            for (Map.Entry<String, String> entry : request.getPathParams().entrySet()) {
                String placeholder = "{" + entry.getKey() + "}";
                finalUrl = finalUrl.replace(placeholder, entry.getValue());
            }
        }

        log.info("URL final: {}", finalUrl);

        if (request.getHeaders() != null) {
            log.info("Headers request: {}", request.getHeaders());
        }

        if (request.getQueryParams() != null) {
            log.info("Query params request: {}", request.getQueryParams());
        }

        if (request.getBody() != null) {
            log.info("Body request: {}", request.getBody());
        }

        try (Client client = createClient(request.getConnectTimeout(), request.getReadTimeout())) {
            WebTarget target = client.target(finalUrl);

            if (request.getQueryParams() != null && !request.getQueryParams().isEmpty()) {
                request.getQueryParams().forEach(target::queryParam);
            }

            Invocation.Builder builder = target.request(MediaType.APPLICATION_JSON);

            if (request.getHeaders() != null && !request.getHeaders().isEmpty()) {
                request.getHeaders().forEach(builder::header);
            }

            Response response = buildRequest(builder, request);
            return handleResponse(response, request);

        }
    }

    private Response buildRequest(Invocation.Builder builder, HttpRequest request) {
        log.info("Método HTTP: {}, Headers enviados: {}", request.getMethod(), builder);

        return switch (request.getMethod()) {
            case GET -> builder.get();
            case POST -> builder.post(Entity.entity(request.getBody(), MediaType.APPLICATION_JSON));
            case PUT -> builder.put(Entity.entity(request.getBody(), MediaType.APPLICATION_JSON));
            case DELETE -> builder.delete();
            case PATCH -> builder.method("PATCH", Entity.entity(request.getBody(), MediaType.APPLICATION_JSON));
            case HEAD -> builder.head();
            case OPTIONS -> builder.options();
            default -> throw new IllegalArgumentException("Método HTTP no soportado: " + request.getMethod());
        };
    }

    private Client createClient(int connectTimeout, int readTimeout) {
        return ClientBuilder.newBuilder()
                .connectTimeout(connectTimeout, TimeUnit.MILLISECONDS)
                .readTimeout(readTimeout, TimeUnit.MILLISECONDS)
                .build();
    }

    @SuppressWarnings("unchecked")
    private <T> T handleResponse(Response response, HttpRequest request) {
        log.info("Respuesta {} {} - Status: {}", request.getMethod(), request.getUrl(), response.getStatus());

        if (response.getStatus() >= 200 && response.getStatus() < 300) {
            try {
                if (request.getResponseType() == Void.class || request.getResponseType() == void.class) {
                    return null;
                }

                T result = (T) response.readEntity(request.getResponseType());
                log.debug("Respuesta exitosa {} {}: {}", request.getMethod(), request.getUrl(), result);
                return result;
            } catch (Exception e) {
                log.error("Error parseando respuesta {} {}: {}", request.getMethod(), request.getUrl(), e.getMessage());
                throw new HttpClientException("Error parseando respuesta", e);
            }
        } else {
            String errorBody = response.readEntity(String.class);
            log.error("Error HTTP {} {} - Status: {} - Body: {}", request.getMethod(), request.getUrl(), response.getStatus(), errorBody);
            throw new HttpClientException("HTTP Error " + response.getStatus() + ": " + errorBody);
        }
    }

    public static class HttpClientException extends RuntimeException {
        public HttpClientException(String message) {
            super(message);
        }

        public HttpClientException(String message, Throwable cause) {
            super(message, cause);
        }
    }
}