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

import com.banesco.common.application.helper.MessageHelper;
import com.banesco.common.application.helper.RequestValidatorHelper;
import com.banesco.common.domain.exception.HttpStatusCodeException;
import com.banesco.common.domain.model.*;
import com.banesco.module.docservice_file_audit_trace.application.usecase.BusinessUseCase;
import com.banesco.module.docservice_file_audit_trace.application.usecase.DocserviceFileAuditTraceUseCase;
import com.banesco.module.docservice_file_audit_trace.domain.dto.request.DocserviceFileAuditTraceRequest;
import com.banesco.module.docservice_file_audit_trace.domain.dto.response.DocserviceFileAuditTraceResponse;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.Response;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@ApplicationScoped
public class DocserviceFileAuditTraceService implements DocserviceFileAuditTraceUseCase {

    private final MessageHelper messageHelper;
    private final RequestValidatorHelper requestValidatorHelper;
    private final BusinessUseCase businessUseCase;

    @Inject
    public DocserviceFileAuditTraceService(
        MessageHelper messageHelper,
        RequestValidatorHelper requestValidatorHelper,
        BusinessUseCase businessUseCase
    ) {
        this.messageHelper = messageHelper;
        this.requestValidatorHelper = requestValidatorHelper;
        this.businessUseCase = businessUseCase;
    }

    @Override
    public Response execute(
        DocserviceFileAuditTraceRequest request
    ) {
        log.info("Iniciando ejecucion para el archivo: {}", request.getDocumentName());

        Response response;

        try {
            validate(request);

            ApiResponse<DocserviceFileAuditTraceResponse> apiResponse = business(request);

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

        return response;
    }

    private void validate(
        DocserviceFileAuditTraceRequest request
    ) {
        requestValidatorHelper.validateRequired(request);
        requestValidatorHelper.validateFieldValues(request);
    }

    private ApiResponse<DocserviceFileAuditTraceResponse> business(
        DocserviceFileAuditTraceRequest request
    ) {
        log.info("Ejecutando llamada al api de negocio: {}", request.getAppId());
        return businessUseCase.execute(request, DocserviceFileAuditTraceResponse.class);
    }
}