package com.banesco.module.service_order_status_control.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.service_order_status_control.application.repository.ApiPrivateRepository;
import com.banesco.module.service_order_status_control.application.usecase.ServiceOrderStatusControlUseCase;
import com.banesco.module.service_order_status_control.domain.dto.request.ServiceOrderStatusControlRequest;
import com.banesco.module.service_order_status_control.domain.dto.response.ServiceOrderStatusControlResponse;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.Response;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@ApplicationScoped
public class ServiceOrderStatusControlService implements ServiceOrderStatusControlUseCase {

    private final MessageHelper messageHelper;
    private final ApiPrivateRepository apiPrivateRepository;

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

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

        Response response;

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

            response = messageHelper.handleSuccess(
                apiResponse.getData(),
                apiResponse.getStatusResponse().getStatusCode()
            );
        } catch (ApiPrivateException e) {
            log.warn("Excepcion de la api privada: {} -> {}", e.getStatusCode(), e.getMessage());
            response = messageHelper.handleException(HttpStatusCodeException.conflict(e.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<ServiceOrderStatusControlResponse> apiPrivate(
        ServiceOrderStatusControlRequest request
    ) {
        log.info("Ejecutando llamada al api privada: {}", request.getClientId());

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