package com.fs.store.cache.impl;

import com.fs.store.cache.IFsUserCacheService;
import com.fs.store.domain.FsUser;
import com.fs.store.service.IFsUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * 用户缓存服务实现类
 *
 * @author fs
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class FsUserCacheServiceImpl implements IFsUserCacheService {

    private final RedisTemplate<String, Object> redisTemplate;
    private final IFsUserService fsUserService;

    @Override
    public FsUser selectFsUserById(Long userId) {
        if (userId == null) {
            throw new IllegalArgumentException("用户ID不能为空！");
        }

        // 尝试从缓存获取
        try {
            String redisKey = String.format("fs:user:%d", userId);
            FsUser user = (FsUser) redisTemplate.opsForValue().get(redisKey);
            if (user != null) {
                log.debug("缓存命中用户信息, userId: {}", userId);
                return user;
            }
        } catch (Exception e) {
            log.error("获取用户缓存异常, userId: {}, 异常信息: {}", userId, e.getMessage(), e);
        }

        log.debug("缓存未命中用户信息, userId: {}, 从数据库查询", userId);
        FsUser user = fsUserService.selectFsUserById(userId);

        return user;
    }
}
