package be.seeseepuff.allowanceplanner.service;

import be.seeseepuff.allowanceplanner.dto.UserDto;
import be.seeseepuff.allowanceplanner.dto.UserWithAllowanceDto;
import be.seeseepuff.allowanceplanner.repository.UserRepository;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class UserService {
    private final UserRepository userRepository;

    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public List<UserDto> getUsers() {
        return userRepository.findAll().stream()
                .map(u -> new UserDto(u.getId(), u.getName()))
                .toList();
    }

    public Optional<UserWithAllowanceDto> getUser(int userId) {
        return userRepository.findById(userId)
                .map(u ->
                {
                    long totalAmount = userRepository.sumHistoryAmount(userId);
                    return new UserWithAllowanceDto(u.getId(), u.getName(), totalAmount / 100.0);
                });
    }

    public boolean userExists(int userId) {
        return userRepository.existsById(userId);
    }
}
