package com.banesco.module.service_order_payment_search.infrastructure.adapter;

import com.banesco.common.domain.exception.HttpStatusCodeException;
import com.banesco.module.payment_order.application.usecase.PaymentOrderUseCase;
import com.banesco.module.payment_order.domain.model.PaymentOrderBol;
import com.banesco.module.payment_order.domain.model.PaymentOrderBole;
import com.banesco.module.service_order_payment_search.application.repository.ApiPrivateRepository;
import com.banesco.module.service_order_payment_search.domain.dto.request.ServiceOrderPaymentSearchRequest;
import com.banesco.module.service_order_payment_search.domain.model.ServicingOrderProcedure;
import com.banesco.module.service_order_payment_search.infrastructure.mapper.ServicingOrderMapper;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
@ApplicationScoped
public class ApiPrivateAdapter implements ApiPrivateRepository {
    private final PaymentOrderUseCase paymentOrderUseCase;

    @Inject
    public ApiPrivateAdapter(
        PaymentOrderUseCase paymentOrderUseCase
    ) {
        this.paymentOrderUseCase = paymentOrderUseCase;
    }

    @Override
    public List<ServicingOrderProcedure> execute(
        ServiceOrderPaymentSearchRequest request
    ) {
        return request.isBole() ? executeBole(request) : executeBol(request);
    }

    private List<ServicingOrderProcedure> executeBole(
        ServiceOrderPaymentSearchRequest request
    ) {
        List<PaymentOrderBole> response = paymentOrderUseCase.execute(
            ServicingOrderMapper.toPaymentRequest(request),
            PaymentOrderBole.class
        );

        log.info("Resultado de las transacciones obtenidas (BOLE): {}", response.size());

        validateResponseNotEmpty(response);

        return ServicingOrderMapper.toBoleModel(response);
    }

    private List<ServicingOrderProcedure> executeBol(
        ServiceOrderPaymentSearchRequest request
    ) {
        List<PaymentOrderBol> response = paymentOrderUseCase.execute(
            ServicingOrderMapper.toPaymentRequest(request),
            PaymentOrderBol.class
        );

        log.info("Resultado de las transacciones obtenidas (BOL): {}", response.size());

        validateResponseNotEmpty(response);

        return ServicingOrderMapper.toBolModel(response);
    }

    private <T> void validateResponseNotEmpty(List<T> response) {
        if (response.isEmpty()) {
            throw HttpStatusCodeException.badRequest("400");
        }
    }
}
