package ru.soune.nocopy.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import ru.soune.nocopy.dto.BaseRequest;
import ru.soune.nocopy.dto.BaseResponse;
import ru.soune.nocopy.dto.MessageCode;
import ru.soune.nocopy.dto.statistic.UserFilesStatisticRequest;
import ru.soune.nocopy.dto.statistic.UserFilesStatisticResponse;
import ru.soune.nocopy.repository.FileEntityRepository;

import java.util.List;

@Component
@RequiredArgsConstructor
@Slf4j
public class StatisticUserFilesHandler implements RequestHandler {

    private final ObjectMapper objectMapper;

    private final FileEntityRepository fileRepository;

    @Override
    public BaseResponse handle(BaseRequest request) throws Exception {
        UserFilesStatisticRequest userFilesStatisticRequest =
                objectMapper.convertValue(request.getMessageBody(), UserFilesStatisticRequest.class);

        int topUsers = userFilesStatisticRequest.getTopUsers();
        String fileMimeType = userFilesStatisticRequest.getFileMimeType();

        List<UserFilesStatisticResponse> files = fileRepository.findTopUsers(topUsers, fileMimeType);

        return new BaseResponse(request.getMsgId(), MessageCode.SUCCESS.getCode(),
                MessageCode.SUCCESS.getDescription(), files);
    }
}
