package com.fs.store.cache.impl;

import com.fs.store.cache.IFsStoreProductAttrCacheService;
import com.fs.store.domain.FsStoreProductAttr;
import com.fs.store.service.IFsStoreProductAttrService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 商品属性信息缓存服务实现
 *
 * @author fs
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class FsStoreProductAttrCacheServiceImpl implements IFsStoreProductAttrCacheService {

    private final RedisTemplate<String, Object> redisTemplate;
    private final IFsStoreProductAttrService productAttrService;

    /**
     * 缓存前缀
     */
    private static final String CACHE_PREFIX = "fs:store:product:attr:";


    @Override
    public FsStoreProductAttr selectFsStoreProductAttrById(Long id) {
        if (id == null) {
            throw new IllegalArgumentException("商品属性id不能为空！");
        }

        // 尝试从缓存获取
        try {
            String redisKey = CACHE_PREFIX + id;
            FsStoreProductAttr productAttr = (FsStoreProductAttr) redisTemplate.opsForValue().get(redisKey);
            if (productAttr != null) {
                log.debug("缓存命中商品属性信息, id: {}", id);
                return productAttr;
            }
        } catch (Exception e) {
            log.error("获取商品属性缓存异常, id: {}, 异常信息: {}", id, e.getMessage(), e);
        }

        log.debug("缓存未命中商品属性信息, id: {}, 从数据库查询", id);
        FsStoreProductAttr productAttr = productAttrService.selectFsStoreProductAttrById(id);
        return productAttr;
    }

}
