package com.banesco.module.payment_initiation_request.application.service;

import com.banesco.common.application.helper.MessageHelper;
import com.banesco.common.domain.exception.*;
import com.banesco.common.domain.model.*;
import com.banesco.module.payment_initiation_request.application.repository.ApiPrivateRepository;
import com.banesco.module.payment_initiation_request.application.usecase.PaymentInitiationRequestUseCase;
import com.banesco.module.payment_initiation_request.domain.dto.request.PaymentInitiationRequestRequest;
import com.banesco.module.payment_initiation_request.domain.dto.response.PaymentInitiationRequestResponse;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.Response;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@ApplicationScoped
public class PaymentInitiationRequestService implements PaymentInitiationRequestUseCase {

    private final MessageHelper messageHelper;
    private final ApiPrivateRepository apiPrivateRepository;

    @Inject
    public PaymentInitiationRequestService(
        MessageHelper messageHelper,
        ApiPrivateRepository apiPrivateRepository
    ) {
        this.messageHelper = messageHelper;
        this.apiPrivateRepository = apiPrivateRepository;
    }

    @Override
    public Response execute(
        PaymentInitiationRequestRequest request
    ) {
        log.info("Iniciando ejecucion para el cliente: {}", request.getPayerId());

        Response response;

        try {
            ApiResponse<PaymentInitiationRequestResponse> apiResponse = apiPrivate(request);

            response = messageHelper.handleSuccess(
                apiResponse.getData(),
                apiResponse.getStatusResponse().getStatusCode()
            );
        } catch (HttpStatusCodeException e) {
            log.error("Excepcion HTTP del api privada: {} - {}", e.getStatusCode(), e.getErrorCode());
            response = messageHelper.handleException(e);
        } catch (Exception e) {
            log.error("Excepcion generica del api privada: {}", e.getMessage());
            response = messageHelper.handleGenericException(e);
        }

        return response;
    }

    private ApiResponse<PaymentInitiationRequestResponse> apiPrivate(
        PaymentInitiationRequestRequest request
    ) {
        log.info("Ejecutando llamada al api privada: {}", request.getPayerId());

        return new ApiResponse<>(
            PaymentInitiationRequestResponse.builder()
                .paymentInitiationTransaction(apiPrivateRepository.execute(request))
                .build(),
            messageHelper.createStatusResponse("200")
        );
    }
}