package ru.soune.nocopy.service.statistic;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import ru.soune.nocopy.dto.statistic.UserDynamicStatisticResponse;
import ru.soune.nocopy.repository.UserRepository;

@Service
@RequiredArgsConstructor
@Slf4j
public class UserDynamicStatisticService {
    private final UserRepository userRepository;

    public UserDynamicStatisticResponse getUserDynamicStatistics() {
        Long totalUsers = userRepository.getTotalUsersCount();
        Long newLast30Days = userRepository.getNewUsersCount(30);
        Long totalUpTo60Days = userRepository.getNewUsersCount(60);
        Long newPrevious30Days = totalUpTo60Days - newLast30Days;
        Double growthPercent = calculateGrowthPercent(newLast30Days, newPrevious30Days);
        Long newCurrentMonth = userRepository.getNewUsersCurrentMonth();
        Long newPreviousMonth = userRepository.getNewUsersPreviousMonth();

        Double monthGrowthPercent = calculateGrowthPercent(newCurrentMonth, newPreviousMonth);

        return UserDynamicStatisticResponse.builder()
                .totalUsers(totalUsers != null ? totalUsers : 0L)
                .newLast30Days(newLast30Days != null ? newLast30Days : 0L)
                .newPrevious30Days(newPrevious30Days != null ? newPrevious30Days : 0L)
                .growthPercent(growthPercent)
                .newCurrentMonth(newCurrentMonth != null ? newCurrentMonth : 0L)
                .newPreviousMonth(newPreviousMonth != null ? newPreviousMonth : 0L)
                .monthGrowthPercent(monthGrowthPercent)
                .build();
    }

    private Double calculateGrowthPercent(Long current, Long previous) {
        if (previous == null || previous == 0) {
            return current != null && current > 0 ? 100.0 : 0.0;
        }

        double percent = ((current - previous) * 100.0) / previous;

        return Math.round(percent * 100.0) / 100.0;
    }
}
