package shop.alien.store.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import shop.alien.entity.store.PlatformShopMembershipOrder;
import shop.alien.entity.store.vo.PlatformShopMembershipOrderCreateResultVo;
import shop.alien.mapper.PlatformShopMembershipOrderMapper;
import shop.alien.store.config.BaseRedisService;
import shop.alien.store.service.PlatformShopMembershipOrderCreateDebounceService;

import java.util.Objects;
import java.util.Optional;

@Slf4j
@Service
@RequiredArgsConstructor
public class PlatformShopMembershipOrderCreateDebounceServiceImpl
        implements PlatformShopMembershipOrderCreateDebounceService {

    static final String REDIS_KEY_PREFIX = "platform:membership:order:create:debounce:";
    private static final long DEBOUNCE_TTL_SECONDS = 15 * 60;

    private final BaseRedisService redisService;
    private final ObjectMapper objectMapper;
    private final PlatformShopMembershipOrderMapper orderMapper;

    static String debounceRedisKey(Integer storeId, Integer planId) {
        return REDIS_KEY_PREFIX + storeId + ":" + planId;
    }

    @Override
    public Optional<PlatformShopMembershipOrderCreateResultVo> getReusablePendingOrder(
            Integer storeId, Integer planId) {
        if (storeId == null || planId == null) {
            return Optional.empty();
        }
        String key = debounceRedisKey(storeId, planId);
        String json = redisService.getString(key);
        if (json == null || json.isEmpty()) {
            return Optional.empty();
        }
        PlatformShopMembershipOrderCreateResultVo vo;
        try {
            vo = objectMapper.readValue(json, PlatformShopMembershipOrderCreateResultVo.class);
        } catch (JsonProcessingException e) {
            log.warn("会员卡创建防抖缓存解析失败, key={}", key, e);
            redisService.delete(key);
            return Optional.empty();
        }
        if (vo == null || vo.getOrderId() == null) {
            redisService.delete(key);
            return Optional.empty();
        }
        PlatformShopMembershipOrder order = orderMapper.selectById(vo.getOrderId());
        if (order == null
                || !Objects.equals(order.getPayStatus(), PlatformShopMembershipOrder.PAY_STATUS_PENDING)
                || !Objects.equals(order.getStoreId(), storeId)
                || !Objects.equals(order.getPlanId(), planId)) {
            redisService.delete(key);
            return Optional.empty();
        }
        return Optional.of(vo);
    }

    @Override
    public void rememberPendingOrder(Integer storeId, Integer planId, PlatformShopMembershipOrderCreateResultVo vo) {
        if (storeId == null || planId == null || vo == null) {
            return;
        }
        String key = debounceRedisKey(storeId, planId);
        try {
            redisService.setString(key, objectMapper.writeValueAsString(vo), DEBOUNCE_TTL_SECONDS);
        } catch (JsonProcessingException e) {
            log.error("会员卡创建防抖写入 Redis 失败, storeId={}, planId={}", storeId, planId, e);
        }
    }

    @Override
    public void clearPendingSlot(Integer storeId, Integer planId) {
        if (storeId == null || planId == null) {
            return;
        }
        redisService.delete(debounceRedisKey(storeId, planId));
    }
}
