package ru.soune.nocopy.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
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.search.GlobalSearchStatisticsRequest;
import ru.soune.nocopy.dto.search.GlobalSearchStatisticsResponse;
import ru.soune.nocopy.service.search.GlobalSearchStatisticsService;

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

    private final ObjectMapper objectMapper;

    private final GlobalSearchStatisticsService statisticsService;

    private final HttpServletRequest httpServletRequest;

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

        Long userId = (Long) httpServletRequest.getAttribute("userId");

        GlobalSearchStatisticsResponse statistics = statisticsService.getStatistics(userId, statRequest.getLimit(),
                statRequest.getDays());

        return BaseResponse.builder()
                .msgId(request.getMsgId())
                .messageBody(statistics)
                .build();
    }
}
