package com.nanri.aiimage.modules.productrisk.service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskShopPayloadDto;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class ProductRiskTaskCacheService {

    private static final long PAYLOAD_TTL_HOURS = 24;

    private final StringRedisTemplate stringRedisTemplate;
    private final ObjectMapper objectMapper;

    public ProductRiskShopPayloadDto getShopMergedPayload(Long taskId, String shopKey) {
        if (taskId == null || taskId <= 0 || shopKey == null || shopKey.isBlank()) {
            return null;
        }
        Object raw = stringRedisTemplate.opsForHash().get(buildShopPayloadKey(taskId), shopKey);
        if (!(raw instanceof String json) || json.isBlank()) {
            return null;
        }
        try {
            return objectMapper.readValue(json, ProductRiskShopPayloadDto.class);
        } catch (Exception ex) {
            throw new BusinessException("读取商品风险店铺缓存失败");
        }
    }

    public void saveShopMergedPayload(Long taskId, String shopKey, ProductRiskShopPayloadDto payload) {
        if (taskId == null || taskId <= 0 || shopKey == null || shopKey.isBlank() || payload == null) {
            return;
        }
        try {
            stringRedisTemplate.opsForHash().put(buildShopPayloadKey(taskId), shopKey, objectMapper.writeValueAsString(payload));
            stringRedisTemplate.expire(buildShopPayloadKey(taskId), Duration.ofHours(PAYLOAD_TTL_HOURS));
        } catch (Exception ex) {
            throw new BusinessException("暂存商品风险店铺缓存失败");
        }
    }

    public void removeShopMergedPayload(Long taskId, String shopKey) {
        if (taskId == null || taskId <= 0 || shopKey == null || shopKey.isBlank()) {
            return;
        }
        stringRedisTemplate.opsForHash().delete(buildShopPayloadKey(taskId), shopKey);
    }

    public Map<String, ProductRiskShopPayloadDto> getAllShopMergedPayload(Long taskId) {
        try {
            Map<Object, Object> raw = stringRedisTemplate.opsForHash().entries(buildShopPayloadKey(taskId));
            if (raw == null || raw.isEmpty()) {
                return Map.of();
            }
            java.util.LinkedHashMap<String, ProductRiskShopPayloadDto> out = new java.util.LinkedHashMap<>();
            for (Map.Entry<Object, Object> entry : raw.entrySet()) {
                if (!(entry.getKey() instanceof String key) || !(entry.getValue() instanceof String val) || val.isBlank()) {
                    continue;
                }
                out.put(key, objectMapper.readValue(val, ProductRiskShopPayloadDto.class));
            }
            return out;
        } catch (Exception ex) {
            throw new BusinessException("读取商品风险缓存失败");
        }
    }

    public void deleteTaskCache(Long taskId) {
        if (taskId == null || taskId <= 0) {
            return;
        }
        stringRedisTemplate.delete(buildShopPayloadKey(taskId));
    }

    private String buildShopPayloadKey(Long taskId) {
        return "product-risk:task:shop-payload:" + taskId;
    }
}
