package com.red.circle.other.app.command.task.query;

import com.alibaba.nacos.common.utils.StringUtils;
import com.red.circle.common.business.dto.cmd.AppExtCommand;
import com.red.circle.other.app.convertor.material.PropsMaterialAppConvertor;
import com.red.circle.other.app.dto.clientobject.activity.ActivityResourceCO;
import com.red.circle.other.app.dto.clientobject.task.CheckInRewardListCO;
import com.red.circle.other.app.dto.cmd.task.CheckInRewardCmd;
import com.red.circle.other.domain.gateway.props.ActivitySourceGroupGateway;
import com.red.circle.other.infra.database.cache.key.CheckInKeys;
import com.red.circle.other.infra.database.cache.service.other.CheckInCacheService;
import com.red.circle.other.inner.enums.activity.PropsActivityTypeEnum;
import java.util.List;
import java.util.Optional;

import com.red.circle.tool.core.date.ZonedDateTimeAsiaRiyadhUtils;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * 每日打卡奖励-信息.
 *
 * @author zongpubin on 2023/10/19
 */
@Service
@AllArgsConstructor
public class CheckInRewardQryExe {

  private final PropsMaterialAppConvertor propsMaterialAppConvertor;
  private final CheckInCacheService checkInCacheService;
  private final ActivitySourceGroupGateway activitySourceGroupGateway;

  public CheckInRewardListCO execute(AppExtCommand cmd, PropsActivityTypeEnum activityType) {

    List<ActivityResourceCO> rewards = propsMaterialAppConvertor
        .toActivityResourceCOList(activitySourceGroupGateway
            .listActivityResource(cmd.requireReqSysOriginEnum(),
                activityType));

    String dailyKey = CheckInKeys.AZIZI_CHECK_IN.getKey("AZIZI_CHECK_IN" + cmd.getReqUserId() + ZonedDateTimeAsiaRiyadhUtils.nowDateToInt());
    Boolean checkIn = checkInCacheService.checkDailyCheckIn(cmd.getReqUserId(), dailyKey);
    Integer days = Optional.ofNullable(checkInCacheService.getCheckInDays(buildKey(cmd.getReqUserId(), activityType.name()))).orElse(0);

    return new CheckInRewardListCO()
        .setDays(days)
        .setCurrentDay(checkIn ? days : Math.min(days + 1, 7) )
        .setRewards(rewards);
  }

  private String buildKey(Long userId, String activityType) {
    if (PropsActivityTypeEnum.DAILY_REGISTER_AZIZI.name().equals(activityType)) {
      return CheckInKeys.AZIZI_SEVEN_CHECK_IN.getKey(userId);
    }
    return CheckInKeys.SEVEN_CHECK_IN.getKey(userId);
  }

}
