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

import com.red.circle.other.app.command.redpacket.GrabUserRedPacketCmdExe;
import com.red.circle.other.app.command.redpacket.SendUserRedPacketCmdExe;
import com.red.circle.other.app.command.redpacket.query.QueryUserRedPacketDetailQryExe;
import com.red.circle.other.app.dto.clientobject.GrabUserRedPacketResultCO;
import com.red.circle.other.app.dto.clientobject.UserRedPacketCO;
import com.red.circle.other.app.dto.cmd.GrabUserRedPacketCmd;
import com.red.circle.other.app.dto.cmd.QueryUserRedPacketDetailCmd;
import com.red.circle.other.app.dto.cmd.SendUserRedPacketCmd;
import com.red.circle.other.app.util.DistributedLockUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * 用户红包服务实现
 */
@Service
@RequiredArgsConstructor
public class UserRedPacketServiceImpl implements UserRedPacketService {

    private final SendUserRedPacketCmdExe sendUserRedPacketCmdExe;
    private final GrabUserRedPacketCmdExe grabUserRedPacketCmdExe;
    private final QueryUserRedPacketDetailQryExe queryUserRedPacketDetailQryExe;
    private final DistributedLockUtil distributedLockUtil;

    @Override
    public UserRedPacketCO sendRedPacket(SendUserRedPacketCmd cmd) {
        String key = "user:red_packet:send:" + cmd.getReqUserId();
        return distributedLockUtil.executeWithLock(key, () -> sendUserRedPacketCmdExe.execute(cmd));
    }

    @Override
    public GrabUserRedPacketResultCO grabRedPacket(GrabUserRedPacketCmd cmd) {
        String key = "user:red_packet:grab:" + cmd.getPacketId() + ":" + cmd.getReqUserId();
        return distributedLockUtil.executeWithLock(key, () -> grabUserRedPacketCmdExe.execute(cmd));
    }

    @Override
    public UserRedPacketCO queryRedPacketDetail(QueryUserRedPacketDetailCmd cmd) {
        return queryUserRedPacketDetailQryExe.execute(cmd);
    }
}
