package com.caliverse.admin.dynamodb.service;

import com.caliverse.admin.Indicators.entity.MoneyLogInfo;
import com.caliverse.admin.domain.entity.Event;
import com.caliverse.admin.domain.entity.Item;
import com.caliverse.admin.domain.entity.Message;
import com.caliverse.admin.dynamodb.domain.atrrib.MoneyAttrib;
import com.caliverse.admin.dynamodb.domain.atrrib.UserNicknameRegistryAttrib;
import com.caliverse.admin.dynamodb.repository.MoneyRepository;
import com.caliverse.admin.dynamodb.repository.SystemMetaMailRepository;
import com.caliverse.admin.dynamodb.repository.UserNicknameRegistryRepository;
import com.caliverse.admin.global.common.annotation.DynamoDBTransaction;
import com.caliverse.admin.global.common.constants.AdminConstants;
import com.caliverse.admin.logs.Indicatordomain.StartEndTime;
import com.caliverse.admin.logs.logservice.LogServiceHelper;
import com.caliverse.admin.logs.logservice.indicators.IndicatorsMoneyService;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class DynamodbService {
    private final DynamoDBOperations DynamoDBOperations;
    private final UserNicknameRegistryRepository userNicknameRegistryRepository;
    private final MoneyRepository moneyRepository;
    private final SystemMetaMailRepository systemMetaMailRepository;

    private final IndicatorsMoneyService moneyService;

    private final ObjectMapper mapper = new ObjectMapper();

    public void saveUserMoney(){
        try {
            List<UserNicknameRegistryAttrib> userList = userNicknameRegistryRepository.findAllAttrib();
            StartEndTime startEndTime = LogServiceHelper.getCurrentLogSearchEndTime(AdminConstants.STAT_DAY_NUM);
            String logTime = startEndTime.getStartTime().substring(0, 10);

            userList.forEach(user -> {
                log.info(String.valueOf(user));
                String guid = user.getUserGuid();
                MoneyAttrib money = moneyRepository.findAttrib(guid);
                MoneyLogInfo moneyInfo = new MoneyLogInfo(logTime, guid, user.getNickname(),money.getGold(), money.getSapphire(), money.getCalium(), money.getRuby());
                moneyService.saveStatLogData(moneyInfo);
            });
        }catch(Exception e){
            log.error(e.getMessage());
        }
    }

    @DynamoDBTransaction
    public void insertSystemMail(Event event){
        systemMetaMailRepository.insert(event);
    }
}
