package com.fs.store.cache.impl;

import com.fs.store.cache.IFsWarehousesCacheService;
import com.fs.store.domain.FsWarehouses;
import com.fs.store.service.IFsWarehousesService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * 仓库信息缓存服务实现类
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class FsWarehousesCacheServiceImpl implements IFsWarehousesCacheService {

    private final RedisTemplate<String, Object> redisTemplate;
    private final IFsWarehousesService fsWarehousesService;

    @Override
    public FsWarehouses selectFsWarehousesById(Long id) {
        if (id == null) {
            throw new IllegalArgumentException("仓库ID不能为空！");
        }

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

        log.debug("缓存未命中仓库信息, id: {}, 从数据库查询", id);
        FsWarehouses warehouses = fsWarehousesService.selectFsWarehousesById(id);

        return warehouses;
    }
}
