package com.banesco.common.application.service;

import com.banesco.common.application.usecase.HttpClientUseCase;
import com.banesco.common.domain.exception.HttpApiResponseException;
import com.banesco.common.domain.exception.HttpStatusCodeException;
import com.banesco.common.domain.model.ApiResponse;
import com.banesco.common.domain.model.HttpRequest;
import com.banesco.common.domain.model.StatusResponse;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.client.*;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import lombok.extern.slf4j.Slf4j;

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

@Slf4j
@ApplicationScoped
public class HttpClientService implements HttpClientUseCase {

    private final ObjectMapper objectMapper;

    @Inject
    public HttpClientService(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @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(request, response);
        } catch (HttpStatusCodeException | HttpApiResponseException e) {
            throw e;
        } catch (Exception e) {
            log.error("Error de conexión {} {}: {}", request.getMethod(), request.getUrl(), e.getMessage());
            throw HttpStatusCodeException.serviceUnavailable(
                    "HTTP_CONNECTION_ERROR",
                    "Error de conexión con el servicio externo: " + e.getMessage()
            );
        }
    }

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

        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(
        HttpRequest request,
        Response response
    ) {
        int statusCode = response.getStatus();
        log.info("Respuesta {} {} - Status: {}", request.getMethod(), request.getUrl(), statusCode);

        try (response) {
            if (statusCode >= 200 && statusCode < 300) {
                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;
            } else {
                String responseBody = response.readEntity(String.class);

                log.error(
                    "Error HTTP {} {} - Status: {} - Body: {}",
                    request.getMethod(),
                    request.getUrl(),
                    statusCode,
                    responseBody
                );

                if (isApiResponseFormat(responseBody)) {
                    ApiResponse<?> apiResponse = parseApiResponse(responseBody, request.getResponseType());
                    throw new HttpApiResponseException(statusCode, apiResponse);
                } else {
                    throw mapHttpStatusToException(statusCode, responseBody);
                }
            }
        } catch (HttpStatusCodeException | HttpApiResponseException e) {
            throw e;
        } catch (Exception e) {
            log.error(
                "Error procesando respuesta {} {}: {}",
                request.getMethod(),
                request.getUrl(),
                e.getMessage()
            );
            throw HttpStatusCodeException.internalServer(
                "ERROR",
                "Error procesando respuesta del servicio externo: " + e.getMessage()
            );
        }
    }

    private boolean isApiResponseFormat(String responseBody) {
        try {
            if (responseBody == null || responseBody.trim().isEmpty()) {
                return false;
            }

            return responseBody.contains("\"data\"") &&
                    responseBody.contains("\"statusResponse\"") &&
                    responseBody.contains("\"statusCode\"") &&
                    responseBody.contains("\"message\"");
        } catch (Exception e) {
            return false;
        }
    }

    private <T> ApiResponse<T> parseApiResponse(
        String responseBody,
        Class<?> responseType
    ) {
        try {
            JavaType javaType;

            if (responseType == ApiResponse.class) {
                javaType = objectMapper.getTypeFactory().constructParametricType(
                    ApiResponse.class,
                    objectMapper.getTypeFactory().constructType(Object.class)
                );

            } else {
                javaType = objectMapper.getTypeFactory().constructParametricType(
                    ApiResponse.class,
                    objectMapper.getTypeFactory().constructType(responseType)
                );
            }

            return objectMapper.readValue(responseBody, javaType);
        } catch (Exception e) {
            log.error("Error parseando ApiResponse: {}", e.getMessage());

            return new ApiResponse<>(
                StatusResponse.builder()
                    .statusCode("500")
                    .message("Error parseando respuesta del servicio")
                    .build()
            );
        }
    }

    private HttpStatusCodeException mapHttpStatusToException(
        int statusCode,
        String errorBody
    ) {
        String errorCode = "HTTP_" + statusCode;
        String defaultMessage = "Error en servicio externo: HTTP " + statusCode;
        String message = errorBody != null && !errorBody.isEmpty()
                ? errorBody
                : defaultMessage;

        return switch (statusCode) {
            case 400 -> HttpStatusCodeException.badRequest(errorCode, message);
            case 401 -> HttpStatusCodeException.unauthorized(errorCode, message);
            case 403 -> HttpStatusCodeException.forbidden(errorCode, message);
            case 404 -> HttpStatusCodeException.notFound(errorCode, message);
            case 405 -> HttpStatusCodeException.methodNotAllowed(errorCode, message);
            case 408 -> HttpStatusCodeException.fromStatusCode(408, errorCode, message);
            case 409 -> HttpStatusCodeException.conflict(errorCode, message);
            case 410 -> HttpStatusCodeException.gone(errorCode, message);
            case 412 -> HttpStatusCodeException.preconditionFailed(errorCode, message);
            case 415 -> HttpStatusCodeException.unsupportedMediaType(errorCode, message);
            case 422 -> HttpStatusCodeException.unprocessableEntity(errorCode, message);
            case 429 -> HttpStatusCodeException.tooManyRequests(errorCode, message);
            case 500 -> HttpStatusCodeException.internalServer(errorCode, message);
            case 501 -> HttpStatusCodeException.notImplemented(errorCode, message);
            case 502 -> HttpStatusCodeException.badGateway(errorCode, message);
            case 503 -> HttpStatusCodeException.serviceUnavailable(errorCode, message);
            case 504 -> HttpStatusCodeException.gatewayTimeout(errorCode, message);
            default -> HttpStatusCodeException.fromStatusCode(statusCode, errorCode, message);
        };
    }
}