package ru.soune.nocopy.service.file;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.soune.nocopy.dto.file.FileTypeStatsDto;
import ru.soune.nocopy.entity.user.ProtectedFileCheck;
import ru.soune.nocopy.repository.ProtectedFileCheckRepository;

import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Slf4j
public class ProtectionsLimitService {

    private final ProtectedFileCheckRepository protectedFileCheckRepository;

    @Transactional(readOnly = true)
    public Map<String, Object> getFileTypeStats(Long userId) {
        ProtectedFileCheck protection = protectedFileCheckRepository
                .findByUserId(userId);

        Map<String, Integer> checksByType = protection.getUsageByType();
        int totalChecks = protection.getPeriodCount();

        if (totalChecks == 0) {
            return Map.of();
        }

        Map<String, Object> collect = checksByType.entrySet().stream()
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        entry -> FileTypeStatsDto.builder()
                                .fileType(entry.getKey())
                                .count(entry.getValue())
                                .build()
                ));

        collect.put("allCountForPeriod", totalChecks);

        return collect;
    }
}
