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

import com.banesco.common.domain.exception.HttpStatusCodeException;
import com.banesco.common.infrastructure.config.DataSourceConfig;
import com.banesco.module.legal_customer_product_directory.application.repository.PersistenceRepository;
import com.banesco.module.legal_customer_product_directory.domain.dto.request.LegalCustomerProductDirectoryRequest;
import com.banesco.module.legal_customer_product_directory.domain.dto.response.SPAccountResponse;
import com.banesco.module.legal_customer_product_directory.domain.model.CustomerProductAndServiceDirectory;
import com.banesco.module.legal_customer_product_directory.infrastructure.persistence.mapper.AccountMapper;
import com.banesco.module.legal_customer_product_directory.infrastructure.persistence.repository.AccountRepository;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
@ApplicationScoped
public class PersistenceAdapter implements PersistenceRepository {

    private final DataSourceConfig dataSourceConfig;
    private final AccountRepository accountRepository;

    @Inject
    public PersistenceAdapter(
        DataSourceConfig dataSourceConfig,
        AccountRepository accountRepository
    ) {
        this.dataSourceConfig = dataSourceConfig;
        this.accountRepository = accountRepository;
    }

    @Override
    public CustomerProductAndServiceDirectory execute(
        LegalCustomerProductDirectoryRequest request
    ) {
        List<SPAccountResponse> accountsFromSP = accountRepository.execute(
            dataSourceConfig, request
        );

        log.info("Cuentas obtenidas por el SP: {}", accountsFromSP.size());

        if(accountsFromSP.isEmpty()) {
            throw HttpStatusCodeException.noContent("VRN02");
        }

        return CustomerProductAndServiceDirectory.builder()
            .accounts(accountsFromSP.stream().map(spAccount ->
                AccountMapper.toAccount(dataSourceConfig, spAccount)
            ).toList())
            .build();
    }
}
