package com.fs.store.cache.impl;

import com.fs.store.cache.IFsUserAddressCacheService;
import com.fs.store.domain.FsUserAddress;
import com.fs.store.service.IFsUserAddressService;
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 FsUserAddressCacheServiceImpl implements IFsUserAddressCacheService {
    private final RedisTemplate<String, Object> redisTemplate;
    private final IFsUserAddressService fsUserAddressService;

    @Override
    public FsUserAddress selectFsUserAddressById(Long id) {
        if (id == null) {
            throw new IllegalArgumentException("用户地址id不能为空！");
        }

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

        log.debug("缓存未命中用户地址信息, id: {}, 从数据库查询", id);
        FsUserAddress userAddress = fsUserAddressService.selectFsUserAddressById(id);

        return userAddress;
    }

}
