package br.gov.sigefp.budget.service;

import br.gov.sigefp.budget.api.dto.EconomicClassificationDTO;
import br.gov.sigefp.budget.domain.EconomicClassification;
import br.gov.sigefp.budget.repository.EconomicClassificationRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class EconomicClassificationService {

    private final EconomicClassificationRepository repository;

    @Transactional(readOnly = true)
    public List<EconomicClassificationDTO> findAll(String type) {
        List<EconomicClassification> list;
        if (type != null && !type.isEmpty()) {
            // Using simple findAll and filtering in memory for small list (20-100 items)
            // Or could use Specification if needed. Current volume is small.
            list = repository.findAll().stream()
                    .filter(e -> e.getType().equalsIgnoreCase(type))
                    .collect(Collectors.toList());
        } else {
            list = repository.findAll();
        }

        return list.stream()
                .sorted(Comparator.comparing(EconomicClassification::getCode))
                .map(this::toDTO)
                .collect(Collectors.toList());
    }

    private EconomicClassificationDTO toDTO(EconomicClassification entity) {
        return EconomicClassificationDTO.builder()
                .id(entity.getId())
                .code(entity.getCode())
                .description(entity.getDescription())
                .type(entity.getType())
                .uemoaCode(entity.getUemoaCode())
                .build();
    }
}
