package com.caliverse.admin.logs.logservice.indicators;

import com.caliverse.admin.Indicators.Indicatordomain.IndicatorsLog;
import com.caliverse.admin.Indicators.entity.NruLogInfo;
import com.caliverse.admin.Indicators.indicatorrepository.IndicatorNruRepository;
import com.caliverse.admin.logs.Indicatordomain.NruMongoLog;
import com.caliverse.admin.logs.logservice.businesslogservice.BusinessLogNruService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Slf4j
@Service
public class IndicatorsNruService {

    @Autowired private IndicatorNruRepository indicatorNruRepository;
    @Autowired private BusinessLogNruService businessLogNruService;

    public void collectCharacterCreateCount(String startTime, String endTime){
        String logTimeStr = startTime.substring(0, 10);
        List<NruMongoLog> indicatorsLog = businessLogNruService.loadBusinessLogData(startTime, endTime, NruMongoLog.class);

        if (indicatorsLog == null || indicatorsLog.isEmpty()) {
            NruLogInfo nruLog = new NruLogInfo(logTimeStr, 0);
            log.info("collectCharacterCreateCount CharacterCreate Log Save logDay: {}, CharacterCreateCount: {}", logTimeStr, nruLog.getNru());
            saveStatLogData(nruLog);
            return;
        }

        for(NruMongoLog mongo_log : indicatorsLog){
            String logDay = mongo_log.getLogDay();

            NruLogInfo nruLog = new NruLogInfo(logDay, mongo_log.getNru());
            log.info("collectCharacterCreateCount CharacterCreate Log Save logDay: {}, CharacterCreateCount: {}", logDay, nruLog.getNru());
            saveStatLogData(nruLog);
        }
    }

    public void saveStatLogData(IndicatorsLog indicatorsLog) {

        if (indicatorsLog instanceof NruLogInfo nruLogInfo) {
            try {
                indicatorNruRepository.save(nruLogInfo);
            } catch (Exception e) {
                log.error("Error Repository Write nruInfo: {}, Message: {}", nruLogInfo, e.getMessage());
            }
        } else {
            log.error("Not instanceof NruLogInfo");
        }
    }

//    public NruLogInfo getNruLogData(LocalDate date) {
//        try {
//            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
//            String logDay = date.format(formatter);
//            List<NruLogInfo> nruLogInfo = indicatorNruRepository.findByLogDay(logDay);
//            if (nruLogInfo == null) {
//                log.info("No NRU data found for date: {}", logDay);
//                return null;
//            }
//            return nruLogInfo.isEmpty() ? null : nruLogInfo.get(0);
//        } catch (Exception e) {
//            log.error("Error while fetching NRU for date: {}", date, e);
//            throw e;
//        }
//    }
}
