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.search.GlobalSearchStatisticsRequest;
import ru.soune.nocopy.dto.search.GlobalSearchStatisticsResponse;
import ru.soune.nocopy.entity.company.Company;
import ru.soune.nocopy.entity.user.AuthToken;
import ru.soune.nocopy.entity.user.User;
import ru.soune.nocopy.repository.AuthTokenRepository;
import ru.soune.nocopy.repository.UserRepository;
import ru.soune.nocopy.service.CompanyService;
import ru.soune.nocopy.service.search.GlobalSearchStatisticsService;
import ru.soune.nocopy.service.user.UserService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

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

    private final ObjectMapper objectMapper;

    private final GlobalSearchStatisticsService statisticsService;

    private final AuthTokenRepository authTokenRepository;

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

        if (statRequest.getToken() == null) {
            throw new IllegalArgumentException("User token is required");
        }

        Optional<AuthToken> tokenOptional =
                authTokenRepository.findByToken(statRequest.getToken());

        if (tokenOptional.isEmpty()) {
            throw new IllegalArgumentException("User token is required");
        }

        Long userId = tokenOptional.orElseThrow().getUser().getId();

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

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