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

import com.banesco.common.application.usecase.HttpClientUseCase;
import com.banesco.common.domain.exception.HttpStatusCodeException;
import com.banesco.common.domain.model.Either;
import com.banesco.common.domain.model.HttpRequest;
import com.banesco.common.infrastructure.config.RestClientConfig;
import com.banesco.module.black_list.application.usecase.BlackListUseCase;
import com.banesco.module.black_list.domain.dto.request.BlackListRequest;
import com.banesco.module.black_list.domain.model.BlackListConfig;
import com.banesco.module.black_list.domain.model.Customer;
import com.banesco.module.black_list.domain.model.OtherIdentDoc;
import com.banesco.module.black_list.domain.model.PersonInfo;
import com.banesco.module.msg_request_header.domain.model.MsgRqHdr;
import com.banesco.module.payment_instruction_request.domain.dto.request.PaymentInstructionRequestRequest;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@ApplicationScoped
public class BlackListClient implements BlackListUseCase {
    private final HttpClientUseCase httpClientUseCase;
    private final BlackListConfig blackListConfig;

    @Inject
    public BlackListClient(
        HttpClientUseCase httpClientUseCase,
        RestClientConfig restClientConfig
    ) {
        this.httpClientUseCase = httpClientUseCase;
        this.blackListConfig = restClientConfig.getBlackListConfig();
        log.info("Configuracion cargada para security-trace: {}", blackListConfig);
    }

    @Override
    public <T, R> Either<T, R> execute(
        PaymentInstructionRequestRequest apiRequest,
        Class<T> responseType,
        Class<R> errorType
    ) {
        BlackListRequest body = getRequest(apiRequest);
        HttpRequest request = HttpRequest.forDirectResponse(
                blackListConfig.getUrl(),
                HttpRequest.HttpMethod.POST,
                responseType,
                errorType
            )
            .withBody(body)
            .withTimeout(
                blackListConfig.getTimeout().getConnect(),
                blackListConfig.getTimeout().getResponse()
            );

        try {
            Either<T, R> response = httpClientUseCase.executeEither(request);

            log.info(
                "Solicitud de lista negra exitosa: {}",
                response.isLeft() && response.getLeft().toString().contains("msgRsHdr=")
            );

            return response;
        } catch (HttpStatusCodeException e) {
            log.error(
                "Error HTTP ejecutando lista negra: {} - {}",
                e.getStatusCode(),
                e.getMessage()
            );

            throw e;
        } catch (Exception e) {
            log.error("Error ejecutando lista negra: {}", e.getMessage());
            throw HttpStatusCodeException.serviceUnavailable("503");
        }
    }

    private BlackListRequest getRequest(
        PaymentInstructionRequestRequest apiRequest
    ) {
        String payeeId = apiRequest.getRecipientId();
        MsgRqHdr msgRqHdr = blackListConfig
            .getRequest()
            .getMsgRqHdr()
            .withOptions(apiRequest.getDevice());

        return BlackListRequest.builder()
            .msgRqHdr(msgRqHdr)
            .customer(Customer.builder()
                .personInfo(PersonInfo.builder()
                    .nationality(payeeId.substring(0, 1).toUpperCase())
                    .otherIdentDoc(OtherIdentDoc.builder()
                        .identSerialNum(getPartyIdNumber(payeeId.substring(1)))
                        .build())
                    .build())
                .build())
            .domain(blackListConfig.getRequest().getDomain())
            .build();
    }

    private String getPartyIdNumber(String partyId) {
        if (partyId == null || partyId.trim().isEmpty()) {
            return null;
        }

        String digits = partyId.replaceAll("\\D", "");

        if (digits.isEmpty()) {
            return null;
        }

        return digits;
    }
}