package com.red.circle.other.app.service.activity.impl;

import com.red.circle.other.app.command.activity.ActivityRewardConfigBadgeQryExe;
import com.red.circle.other.app.command.activity.ActivityRewardConfigQryExe;
import com.red.circle.other.app.command.activity.ClaimActivityRewardBadgeExe;
import com.red.circle.other.app.command.activity.ClaimActivityRewardExe;
import com.red.circle.other.app.dto.clientobject.activity.ActivityRewardConfigCO;
import com.red.circle.other.app.dto.clientobject.activity.ClaimRewardResultCO;
import com.red.circle.other.app.dto.cmd.activity.ActivityRewardConfigCmd;
import com.red.circle.other.app.dto.cmd.activity.ClaimActivityRewardCmd;
import com.red.circle.other.app.service.activity.ActivityRewardConfigService;
import com.red.circle.other.app.util.DistributedLockUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 活动奖励配置服务实现
 */
@Service
@RequiredArgsConstructor
public class ActivityRewardConfigServiceImpl implements ActivityRewardConfigService {

    private final ActivityRewardConfigQryExe activityRewardConfigQryExe;
    private final ClaimActivityRewardExe claimActivityRewardExe;
    private final ActivityRewardConfigBadgeQryExe activityRewardConfigBadgeQryExe;
    private final ClaimActivityRewardBadgeExe claimActivityRewardBadgeExe;
    private final DistributedLockUtil distributedLockUtil;

    private static final String CLAIM_LOCK_PREFIX = "activity:reward:claim:lock";

    @Override
    public List<ActivityRewardConfigCO> listRewardConfigs(ActivityRewardConfigCmd cmd) {
        return activityRewardConfigQryExe.execute(cmd);
    }

    @Override
    public ClaimRewardResultCO claimReward(ClaimActivityRewardCmd cmd) {
        String lockKey = DistributedLockUtil.buildLockKey(
            CLAIM_LOCK_PREFIX, 
            cmd.getReqUserId(), 
            cmd.getRuleId()
        );

        return distributedLockUtil.executeWithLock(
            lockKey,
            () -> claimActivityRewardExe.execute(cmd)
        );
    }

    @Override
    public List<ActivityRewardConfigCO> listRewardConfigsBadge(ActivityRewardConfigCmd cmd) {
        return activityRewardConfigBadgeQryExe.execute(cmd);
    }

    @Override
    public ClaimRewardResultCO claimRewardBadge(ClaimActivityRewardCmd cmd) {
        String lockKey = DistributedLockUtil.buildLockKey(
                CLAIM_LOCK_PREFIX,
                cmd.getReqUserId(),
                cmd.getRuleId()
        );

        return distributedLockUtil.executeWithLock(
                lockKey,
                () -> claimActivityRewardBadgeExe.execute(cmd)
        );
    }

}
