package ru.soune.nocopy.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
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.TariffStatisticFullResponse;
import ru.soune.nocopy.dto.statistic.TariffStatisticRequest;
import ru.soune.nocopy.dto.statistic.TariffStatisticResponse;
import ru.soune.nocopy.repository.TariffInfoRepository;

import java.util.List;

@Component
@AllArgsConstructor
public class StatisticTariffInfoFileHandler implements RequestHandler {

    private ObjectMapper objectMapper;

    private TariffInfoRepository tariffInfoRepository;

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

        boolean activeOnly = tariffRequest.getActiveOnly() != null ? tariffRequest.getActiveOnly() : true;
        List<Object[]> results = tariffInfoRepository.getTariffStatisticsNative(activeOnly);

        List<TariffStatisticResponse> tariffs = results.stream()
                .map(row -> new TariffStatisticResponse(
                        (String) row[0],
                        ((Number) row[1]).longValue(),
                        ((Number) row[2]).doubleValue()
                ))
                .toList();

        TariffStatisticFullResponse statistics = new TariffStatisticFullResponse(tariffs);

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