package com.fs.store.cache.impl;

import com.fs.store.cache.IFsStoreProductPackageCacheService;
import com.fs.store.domain.FsStoreProductPackage;
import com.fs.store.mapper.FsStoreProductPackageMapper;
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 IFsStoreProductPackageServiceImpl implements IFsStoreProductPackageCacheService {
    private final RedisTemplate<String,Object> redisTemplate;
    private final FsStoreProductPackageMapper fsStoreProductPackageMapper;

    @Override
    public FsStoreProductPackage selectFsStoreProductPackageById(Long packageId) {
        if(packageId == null) {
            throw new IllegalArgumentException("套餐包id不能为空！");
        }
        // 尝试从缓存获取
        try {
            String redisKey = String.format("fs:store:product:package:%d", packageId);
            FsStoreProductPackage productPackage = (FsStoreProductPackage) redisTemplate.opsForValue().get(redisKey);
            if(productPackage != null) {
                log.debug("缓存命中套餐包信息, packageId: {}", packageId);
                return productPackage;
            }
        } catch (Exception e) {
            log.error("获取套餐包缓存异常, packageId: {}, 异常信息: {}", packageId, e.getMessage(), e);
        }

        log.debug("缓存未命中套餐包信息, packageId: {}, 从数据库查询", packageId);
        FsStoreProductPackage productPackage = fsStoreProductPackageMapper.selectFsStoreProductPackageById(packageId);

        return productPackage;
    }
}
