package ru.soune.nocopy.service.statistic;

import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import ru.soune.nocopy.dto.complaint.ComplaintRequest;
import ru.soune.nocopy.dto.statistic.ComplaintStatisticResponse;
import ru.soune.nocopy.entity.complaint.ComplaintStatus;
import ru.soune.nocopy.repository.ComplaintEntityRepository;
import ru.soune.nocopy.service.complaint.ComplaintEntityService;

import java.util.HashMap;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class ComplaintStatisticService {

    private final ComplaintEntityRepository complaintEntityRepository;

    private final ComplaintEntityService complaintService;

    public ComplaintStatisticResponse complaintStatistic(ComplaintRequest complaintRequest) {
        return ComplaintStatisticResponse.builder()
                .totalComplaints(complaintEntityRepository.getTotalComplaintsCount())
                .totalCancelled(complaintEntityRepository.getTotalComplaintsCountByStatus(ComplaintStatus.CANCELLED))
                .totalCreated(complaintEntityRepository.getTotalComplaintsCountByStatus(ComplaintStatus.CREATED))
                .totalCompleted(complaintEntityRepository.getTotalComplaintsCountByStatus(ComplaintStatus.COMPLETED))
                .totalInWork(complaintEntityRepository.getTotalComplaintsCountByStatus(ComplaintStatus.IN_WORK))
                .complaints(handleGetAll(complaintRequest))
                .build();
    }

    private Map<String, Object> handleGetAll(ComplaintRequest req) {
        Pageable pageable = PageRequest.of(
                req.getPage() != null ? req.getPage() : 0,
                req.getSize() != null ? req.getSize() : 5,
                Sort.by(Sort.Direction.fromString(
                                req.getSortDirection() != null ? req.getSortDirection() : "desc"),
                        req.getSortBy() != null ? req.getSortBy() : "updatedAt"));

        var page = complaintService.getAllComplaints(pageable);

        Map<String, Object> data = new HashMap<>();
        data.put("content", page.getContent());
        data.put("page", page.getNumber() + 1);
        data.put("size", page.getSize());
        data.put("totalElements", page.getTotalElements());
        data.put("totalPages", page.getTotalPages());

        return data;
    }
}
