package com.fs.store.cache.impl;

import com.fs.store.cache.IFsExpressCacheService;
import com.fs.store.domain.FsExpress;
import com.fs.store.service.IFsExpressService;
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 FsExpressCacheServiceImpl implements IFsExpressCacheService {

    private final RedisTemplate<String, Object> redisTemplate;
    private final IFsExpressService fsExpressService;

    @Override
    public FsExpress selectFsExpressByOmsCode(String omsCode) {
        if (omsCode == null || omsCode.trim().isEmpty()) {
            throw new IllegalArgumentException("快递编码不能为空！");
        }

        // 尝试从缓存获取
        try {
            String redisKey = String.format("fs:express:%s", omsCode);
            FsExpress fsExpress = (FsExpress) redisTemplate.opsForValue().get(redisKey);
            if (fsExpress != null) {
                log.debug("缓存命中快递信息, omsCode: {}", omsCode);
                return fsExpress;
            }
        } catch (Exception e) {
            log.error("获取快递缓存异常, omsCode: {}, 异常信息: {}", omsCode, e.getMessage(), e);
        }

        log.debug("缓存未命中快递信息, omsCode: {}, 从数据库查询", omsCode);
        FsExpress fsExpress = fsExpressService.selectFsExpressByOmsCode(omsCode);

        return fsExpress;
    }
}
