package com.red.circle.other.infra.database.cache.service.other.impl;

import com.red.circle.other.infra.database.cache.service.other.UserRedPacketCacheService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 用户红包缓存服务实现
 */
@Service
@RequiredArgsConstructor
public class UserRedPacketCacheServiceImpl implements UserRedPacketCacheService {

    private final RedisTemplate<String, Object> redisTemplate;

    private static final String PACKET_KEY_PREFIX = "user:red_packet:";
    private static final String GRABBED_KEY_PREFIX = "user:red_packet:grabbed:";

    @Override
    public void setRedPacket(String packetId, Map<String, Object> data, long expireSeconds) {
        String key = PACKET_KEY_PREFIX + packetId;
        redisTemplate.opsForHash().putAll(key, data);
        redisTemplate.expire(key, expireSeconds, TimeUnit.SECONDS);
    }

    @Override
    public Map<Object, Object> getRedPacket(String packetId) {
        String key = PACKET_KEY_PREFIX + packetId;
        return redisTemplate.opsForHash().entries(key);
    }

    @Override
    public boolean hasUserGrabbed(String packetId, Long userId) {
        String key = GRABBED_KEY_PREFIX + packetId + ":" + userId;
        return Boolean.TRUE.equals(redisTemplate.hasKey(key));
    }

    @Override
    public boolean setUserGrabbedFlag(String packetId, Long userId, long expireSeconds) {
        String key = GRABBED_KEY_PREFIX + packetId + ":" + userId;
        return Boolean.TRUE.equals(redisTemplate.opsForValue().setIfAbsent(key, "1", expireSeconds, TimeUnit.SECONDS));
    }

    @Override
    public void deleteRedPacket(String packetId) {
        String key = PACKET_KEY_PREFIX + packetId;
        redisTemplate.delete(key);
    }

    @Override
    public void deleteUserGrabbedFlag(String packetId, Long userId) {
        String key = GRABBED_KEY_PREFIX + packetId + ":" + userId;
        redisTemplate.delete(key);
    }
}
