package com.banesco.module.legal_customer_product_directory.infrastructure.client;

import com.banesco.common.application.usecase.HttpClientUseCase;
import com.banesco.common.domain.exception.ServiceUnavailableException;
import com.banesco.common.domain.exception.SuccessException;
import com.banesco.common.domain.model.ApiResponse;
import com.banesco.common.domain.model.HttpRequest;
import com.banesco.common.infrastructure.config.RestClientConfig;
import com.banesco.module.legal_customer_product_directory.application.usecase.BusinessUseCase;
import lombok.extern.slf4j.Slf4j;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;

import java.util.Map;

@Slf4j
@ApplicationScoped
public class BusLegalCustomerDirectoryClient implements BusinessUseCase {
    private final HttpClientUseCase httpClientUseCase;
    private final RestClientConfig.BusConfig busConfig;

    @Inject
    public BusLegalCustomerDirectoryClient(
        HttpClientUseCase httpClientUseCase,
        RestClientConfig restClientConfig
    ) {
        this.httpClientUseCase = httpClientUseCase;
        this.busConfig = restClientConfig.getBusLegalCustomerConfig();
        log.info("Configuración cargada para bus-legal-customer-directory: {}", busConfig);
    }

    @Override
    public <T> ApiResponse<T> execute(
        boolean isMock,
        String customerIbsNumber,
        Map<String, String> queryParams,
        Map<String, String> headers,
        Class<T> responseType
    ) {
        log.info("Consultando información del cliente: {}", customerIbsNumber);

        if(isMock) {
            throw new SuccessException("200", null);
        }

        try {
            HttpRequest request = HttpRequest.builder()
                .url(busConfig.getUrl())
                .method(HttpRequest.HttpMethod.GET)
                .pathParams(Map.of("customerIbsNumber", customerIbsNumber))
                .queryParams(queryParams)
                .headers(headers)
                .responseType(responseType)
                .connectTimeout(busConfig.getTimeout().getConnect())
                .readTimeout(busConfig.getTimeout().getResponse())
                .build();

            log.debug("Request configurado: {}", request);

            return httpClientUseCase.execute(request);
        } catch (Exception e) {
            log.error("Error consultando cliente {}: {}", customerIbsNumber, e.getMessage());
            throw new ServiceUnavailableException("503", e.getMessage(), null);
        }
    }
}