package com.banesco.infrastructure.rest.repositories;

import com.banesco.common.domain.dto.bian.device.JsonHelper;
import com.banesco.common.domain.dto.bian.device.LoggerHelper;
import com.banesco.common.domain.dto.bian.response.StatusResponse;
import com.banesco.common.domain.model.ApiConfig;
import com.banesco.commons.config.StatusCodes;
import com.banesco.commons.utils.ResponseUtil;
import com.banesco.infrastructure.dtos.card.BusUpdateCardStatusRequest;
import com.banesco.infrastructure.dtos.card.BusUpdateCardStatusResponse;
import com.banesco.infrastructure.rest.clients.BusUpdateCardStatusRestClient;
import io.quarkus.runtime.annotations.RegisterForReflection;
import jakarta.ws.rs.ClientErrorException;
import jakarta.ws.rs.core.Response;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.microprofile.rest.client.RestClientBuilder;

import java.net.URI;
import java.util.concurrent.TimeUnit;


@RegisterForReflection
@Slf4j
public class PaymentCardRepository {


    private final BusUpdateCardStatusRestClient restClient;

    private final String OPERATION_NAME = "BUS_UPDATE_CARD_STATUS";


    public PaymentCardRepository(ApiConfig apiConfig) {

        restClient = RestClientBuilder.newBuilder().baseUri(
                        URI.create(apiConfig.getUrl())
                ).
                connectTimeout(apiConfig.getTimeout().getConnect(), TimeUnit.MILLISECONDS)
                .readTimeout(apiConfig.getTimeout().getResponse(), TimeUnit.MILLISECONDS)
                .build(BusUpdateCardStatusRestClient.class);

    }


    public StatusResponse updateCardStatus(BusUpdateCardStatusRequest request) {

        try {


            log.info(LoggerHelper.buildInfoPrivateRequest(request.getRequestId(), OPERATION_NAME, JsonHelper.getJsonFromObject(request)));

            Response responseHttp = restClient.invoke(request);

            BusUpdateCardStatusResponse response = responseHttp.readEntity(BusUpdateCardStatusResponse.class);
            log.info(LoggerHelper.buildInfoPrivateResponse(request.getRequestId(), OPERATION_NAME, JsonHelper.getJsonFromObject(response)));


            return response.getStatusResponse();


        } catch (ClientErrorException e) {
            log.error(LoggerHelper.buildError(OPERATION_NAME + " - " + request.getRequestId(), "Error calling API: " + e.getMessage()));
            return ResponseUtil.mapErrorResponse(request.getRequestId(), StatusCodes.FAILED_DEPENDENCY);
        } catch (Exception e) {
            log.error(LoggerHelper.buildError(OPERATION_NAME + " - " + request.getRequestId(), "Error interno callig API: " + e.getMessage()));
            return ResponseUtil.mapErrorResponse(request.getRequestId(), StatusCodes.INTERNAL_ERROR);
        }

    }
}
