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

import com.red.circle.other.app.dto.cmd.activity.RankingDataUpdateCmd;
import com.red.circle.other.infra.database.mongo.entity.activity.RankingActivityRecord;
import com.red.circle.other.infra.gateway.RankingActivityGateway;
import com.red.circle.other.domain.ranking.RankingActivityType;
import com.red.circle.other.domain.ranking.RankingCycleType;
import com.red.circle.other.domain.ranking.RankingDimension;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.Optional;

/**
 * 累计排行数据命令执行器
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class RankingDataAccumulateCmdExe {

    private final RankingActivityGateway rankingActivityGateway;

    @Transactional(rollbackFor = Exception.class)
    public Boolean execute(RankingDataUpdateCmd cmd) {
        // 获取枚举
        RankingActivityType activityType = RankingActivityType.getByCode(cmd.getActivityType());
        RankingCycleType cycleType = RankingCycleType.getByCode(cmd.getCycleType());
        RankingDimension dimension = RankingDimension.getByCode(cmd.getDimension());

        RankingActivityRecord record = new RankingActivityRecord();
        record.setSysOrigin(cmd.getReqSysOrigin().getOrigin());
        record.setUserId(cmd.getUserId());
        record.setUserSex(cmd.getUserSex());
        record.setActivityType(activityType);
        record.setCycleType(cycleType);
        record.setCycleKey(cmd.getCycleKey());
        record.setDimension(dimension);
        record.setExtData(cmd.getExtData());
        record.setExpiredTime(calculateExpiredTime(cycleType, cmd.getCycleKey()));

        // 累计数据
        rankingActivityGateway.accumulateRankingData(record, cmd.getIncrementQuantity());

        return true;
    }

    /**
     * 计算过期时间
     */
    private Timestamp calculateExpiredTime(RankingCycleType cycleType, String cycleKey) {
        // 简化实现：统一设置为30天后过期
        long expiredMillis = System.currentTimeMillis() + 30L * 24 * 60 * 60 * 1000;
        return new Timestamp(expiredMillis);
    }
}