package com.banesco.module.legal_customer_product_directory.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.legal_customer_product_directory.application.repository.PersistenceRepository;
import com.banesco.module.legal_customer_product_directory.application.usecase.LegalCustomerProductDirectoryUseCase;
import com.banesco.module.legal_customer_product_directory.domain.dto.request.LegalCustomerProductDirectoryRequest;
import com.banesco.module.legal_customer_product_directory.domain.dto.response.LegalCustomerProductDirectoryResponse;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@ApplicationScoped
public class LegalCustomerProductDirectoryService implements LegalCustomerProductDirectoryUseCase {

    private final MessageHelper messageHelper;
    private final PersistenceRepository persistenceRepository;

    @Inject
    public LegalCustomerProductDirectoryService(
        MessageHelper messageHelper,
        PersistenceRepository persistenceRepository
    ) {
        this.messageHelper = messageHelper;
        this.persistenceRepository = persistenceRepository;
    }

    @Override
    public ApiResponse<LegalCustomerProductDirectoryResponse> execute(
        LegalCustomerProductDirectoryRequest request
    ) {
        log.info("Iniciando ejecución para el cliente: {}", request.getCustomerIbsNumber());

        try {
            return storeProcedure(request);
        } catch (PersistenceException e) {
            log.warn("Excepción de la persistencia del sp: {} -> {}", e.getErrorCode(), e.getMessage());
            throw HttpStatusCodeException.badRequest(e.getErrorCode());
        } catch (HttpStatusCodeException e) {
            log.error("Excepción HTTP del api de dominio: {} - {}", e.getStatusCode(), e.getErrorCode());
            throw e;
        } catch (Exception e) {
            log.error("Excepción genérica del api de dominio: {}", e.getMessage());
            throw e;
        }
    }

    private ApiResponse<LegalCustomerProductDirectoryResponse> storeProcedure(
        LegalCustomerProductDirectoryRequest request
    ) {
        log.info("Calling persistence repository for client: {}", request.getCustomerIbsNumber());

        return new ApiResponse<>(
            LegalCustomerProductDirectoryResponse.builder()
                .customerProductAndServiceDirectory(persistenceRepository.execute(request))
                .build(),
            messageHelper.createStatusResponse("200")
        );
    }
}