package shop.alien.store.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import shop.alien.entity.store.PlatformShopMembershipOrder;
import shop.alien.mapper.PlatformShopMembershipOrderMapper;
import shop.alien.store.config.BaseRedisService;
import shop.alien.store.listener.RedisKeyExpirationHandler;
import shop.alien.store.service.PlatformShopMembershipOrderCreateDebounceService;
import shop.alien.store.service.PlatformShopMembershipOrderPaymentTimeoutService;

import javax.annotation.PostConstruct;
import java.util.Date;

@Slf4j
@Service
@RequiredArgsConstructor
public class PlatformShopMembershipOrderPaymentTimeoutServiceImpl
        implements PlatformShopMembershipOrderPaymentTimeoutService {

    /** 与律师咨询订单超时机制一致，依赖 Redis notify-keyspace-events 含 Ex */
    public static final String REDIS_KEY_PREFIX = "platform:membership:order:payment:timeout:";

    private static final long TIMEOUT_SECONDS = 15 * 60;

    private final BaseRedisService redisService;
    private final RedisKeyExpirationHandler expirationHandler;
    private final PlatformShopMembershipOrderMapper orderMapper;
    private final PlatformShopMembershipOrderCreateDebounceService orderCreateDebounceService;

    @PostConstruct
    public void init() {
        expirationHandler.registerHandler(REDIS_KEY_PREFIX, this::onExpiredKey);
    }

    private void onExpiredKey(String expiredKey) {
        String suffix = expiredKey.substring(REDIS_KEY_PREFIX.length());
        Integer orderId;
        try {
            orderId = Integer.valueOf(suffix);
        } catch (NumberFormatException e) {
            log.warn("会员卡订单超时 key 格式无效: {}", expiredKey);
            return;
        }
        try {
            LambdaUpdateWrapper<PlatformShopMembershipOrder> u = new LambdaUpdateWrapper<>();
            u.eq(PlatformShopMembershipOrder::getId, orderId);
            u.eq(PlatformShopMembershipOrder::getPayStatus, PlatformShopMembershipOrder.PAY_STATUS_PENDING);
            u.set(PlatformShopMembershipOrder::getPayStatus, PlatformShopMembershipOrder.PAY_STATUS_CLOSED);
            u.set(PlatformShopMembershipOrder::getUpdatedTime, new Date());
            int rows = orderMapper.update(null, u);
            if (rows > 0) {
                log.info("会员卡订单超时未支付已关闭, orderId={}", orderId);
                PlatformShopMembershipOrder closed = orderMapper.selectById(orderId);
                if (closed != null) {
                    orderCreateDebounceService.clearPendingSlot(closed.getStoreId(), closed.getPlanId());
                }
            }
        } catch (Exception e) {
            log.error("会员卡订单超时关单失败, orderId={}", orderId, e);
        }
    }

    @Override
    public void scheduleClosePendingOrder(Integer orderId) {
        if (orderId == null) {
            return;
        }
        String key = REDIS_KEY_PREFIX + orderId;
        redisService.setString(key, String.valueOf(orderId), TIMEOUT_SECONDS);
        log.info("会员卡订单支付超时监听已设置, orderId={}, ttlSeconds={}", orderId, TIMEOUT_SECONDS);
    }

    @Override
    public void cancelClosePendingOrder(Integer orderId) {
        if (orderId == null) {
            return;
        }
        redisService.delete(REDIS_KEY_PREFIX + orderId);
    }
}
