package com.luojia_channel.modules.user.utils;

import cn.hutool.core.lang.UUID;
import com.luojia_channel.common.domain.UserDTO;
import com.luojia_channel.common.exception.UserException;
import com.luojia_channel.common.utils.RedisUtil;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

import static com.luojia_channel.modules.user.constant.UserConstant.*;

/**
 * 这是生成匿名用户的工具类，用于前端展示，并支持后端校验
 */
@Component
@RequiredArgsConstructor
public class AnonymousUserUtil {
    private final RedisUtil redisUtil;
    private final RedissonClient redissonClient;

    /**
     * 生成匿名用户id
     * @param userDTO
     * @return
     */
    public String generateAnonymousId(UserDTO userDTO){
        String anonymousId = ANONYMOUS_USER_PREFIX + UUID.randomUUID().toString().replace("-", "");
        String cacheKey = ANONYMOUS_KEY_PREFIX + anonymousId;
        String lockKey = ANONYMOUS_KEY_PREFIX + userDTO.getUserId();
        RLock lock = redissonClient.getLock(lockKey);
        boolean tryLock = lock.tryLock();
        if(!tryLock){
            throw new UserException("匿名频繁，请稍后重试");
        }
        try {
            redisUtil.set(cacheKey, userDTO, EXPIRE_TIME_MINUTES, TimeUnit.MINUTES);
        }finally {
            lock.unlock();
        }
        return anonymousId;
    }

    /**
     * 解析匿名用户
     * @param anonymousId
     * @return
     */
    public UserDTO getRealUser(String anonymousId){
        String cacheKey = ANONYMOUS_KEY_PREFIX + anonymousId;
        UserDTO user = redisUtil.get(cacheKey, UserDTO.class);
        if(user == null){
            throw new UserException("匿名用户不存在或已过期");
        }
        return user;
    }


}
