package com.erp.inventory.service.impl;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;

/**
 * 库存服务幂等性工具
 * 使用Redis实现库存操作的幂等性
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class StockIdempotencyService {

    private final RedisTemplate<String, Object> redisTemplate;

    private static final String IDEMPOTENT_KEY_PREFIX = "stock:idempotent:";
    private static final Duration DEFAULT_TTL = Duration.ofHours(24);

    /**
     * 检查是否重复请求
     */
    public boolean isDuplicate(String key) {
        String redisKey = IDEMPOTENT_KEY_PREFIX + key;
        return Boolean.TRUE.equals(redisTemplate.hasKey(redisKey));
    }

    /**
     * 标记请求已处理
     */
    public void markProcessed(String key, Object value) {
        String redisKey = IDEMPOTENT_KEY_PREFIX + key;
        redisTemplate.opsForValue().set(redisKey, value, DEFAULT_TTL);
    }

    /**
     * 获取已处理结果
     */
    public Object getProcessedResult(String key) {
        String redisKey = IDEMPOTENT_KEY_PREFIX + key;
        return redisTemplate.opsForValue().get(redisKey);
    }

    /**
     * 库存扣减幂等键：skuCode + warehouseId + orderId
     */
    public String buildDeductKey(String skuCode, Long warehouseId, String relatedNo) {
        return skuCode + ":" + warehouseId + ":" + relatedNo;
    }

    /**
     * 库存锁定幂等键
     */
    public String buildLockKey(String skuCode, Long warehouseId, String relatedNo) {
        return "lock:" + skuCode + ":" + warehouseId + ":" + relatedNo;
    }

    /**
     * 库存解锁幂等键
     */
    public String buildUnlockKey(String skuCode, Long warehouseId, String relatedNo) {
        return "unlock:" + skuCode + ":" + warehouseId + ":" + relatedNo;
    }
}
