package com.caliverse.admin.domain.service;

import com.caliverse.admin.Indicators.Indicatorsservice.aggregationservice.*;
import com.caliverse.admin.Indicators.entity.*;
import com.caliverse.admin.domain.entity.Currencys;
import com.caliverse.admin.domain.entity.LandInfo;
import com.caliverse.admin.domain.entity.ROUTE;
import com.caliverse.admin.domain.request.LogGenericRequest;
import com.caliverse.admin.domain.response.IndicatorsResponse;
import com.caliverse.admin.domain.response.LandResponse;
import com.caliverse.admin.domain.response.LogResponse;
import com.caliverse.admin.global.common.code.CommonCode;
import com.caliverse.admin.global.common.code.ErrorCode;
import com.caliverse.admin.global.common.exception.RestApiException;
import com.caliverse.admin.global.common.utils.CommonUtils;
import com.caliverse.admin.global.common.utils.ExcelUtils;
import com.caliverse.admin.logs.Indicatordomain.GenericMongoLog;
import com.caliverse.admin.logs.logservice.businesslogservice.BusinessLogGenericService;
import com.caliverse.admin.logs.logservice.indicators.IndicatorsDauService;
import com.caliverse.admin.logs.logservice.indicators.IndicatorsMcuService;
import com.caliverse.admin.logs.logservice.indicators.IndicatorsNruService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mongodb.MongoCommandException;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.mongodb.UncategorizedMongoDbException;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Slf4j
public class LogService {

    private final BusinessLogGenericService businessLogGenericService;

    public LogResponse genericLogList(LogGenericRequest logGenericRequest){
        int page = logGenericRequest.getPageNo();
        int size = logGenericRequest.getPageSize();

        LocalDateTime startDt = logGenericRequest.getStartDt().plusHours(9);
        LocalDateTime endDt = logGenericRequest.getEndDt().plusHours(9).plusDays(1);

        logGenericRequest.setStartDt(startDt);
        logGenericRequest.setEndDt(endDt);

//        List<Map<String, Object>> logList = businessLogGenericService.loadBusinessLogData(logGenericRequest);
        List<GenericMongoLog> logList = new ArrayList<>();
        try{
            logList = businessLogGenericService.loadBusinessLogData(logGenericRequest, GenericMongoLog.class);
        }catch(UncategorizedMongoDbException e){
            if (e.getMessage().contains("Sort exceeded memory limit")) {
                log.error("MongoDB Query memory limit error: {}", e.getMessage());
                return LogResponse.builder()
                        .status(CommonCode.ERROR.getHttpStatus())
                        .result(ErrorCode.ERROR_LOG_MEMORY_LIMIT.toString())
                        .build();
            } else {
                log.error("MongoDB Query error", e);
                return LogResponse.builder()
                        .status(CommonCode.ERROR.getHttpStatus())
                        .result(ErrorCode.ERROR_MONGODB_QUERY.toString())
                        .build();
            }
        }catch (Exception e){
            log.error("businessLog error", e);
        }

        int totalItems = logList.size();
        int totalPages = (int) Math.ceil((double) totalItems / size);
        page = (totalItems > 0 && page > totalPages) ? totalPages : page;

        List<GenericMongoLog> pagedList = (totalItems == 0) ?
                new ArrayList<>() :
                logList.subList((page - 1) * size, Math.min((page - 1) * size + size, totalItems));

        return LogResponse.builder()
             .resultData(LogResponse.ResultData.builder()
                     .genericList(pagedList)
                     .total(pagedList.size())
                     .totalAll(totalItems)
                     .pageNo(logGenericRequest.getPageNo() != null ?
                             page : 1)
                     .build())
             .status(CommonCode.SUCCESS.getHttpStatus())
             .result(CommonCode.SUCCESS.getResult())
             .build();

    }
}
