package com.admin.common.task;

import com.admin.common.utils.GostUtil;
import com.admin.entity.ChainTunnel;
import com.admin.entity.Forward;
import com.admin.entity.UserTunnel;
import com.admin.service.ChainTunnelService;
import com.admin.service.ForwardService;
import com.admin.service.UserTunnelService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/** 定期关闭已到期的单条转发。 */
@Slf4j
@Component
public class ExpireForwardAsync {

    @Resource
    ForwardService forwardService;

    @Resource
    ChainTunnelService chainTunnelService;

    @Resource
    UserTunnelService userTunnelService;

    @Scheduled(fixedDelay = 60000, initialDelay = 10000)
    public void pauseExpiredForwards() {
        long now = System.currentTimeMillis();
        List<Forward> expiredForwards = forwardService.list(new QueryWrapper<Forward>()
                .eq("status", 1)
                .gt("exp_time", 0)
                .le("exp_time", now));

        for (Forward forward : expiredForwards) {
            try {
                UserTunnel userTunnel = userTunnelService.getOne(new QueryWrapper<UserTunnel>()
                        .eq("user_id", forward.getUserId())
                        .eq("tunnel_id", forward.getTunnelId()));
                int userTunnelId = userTunnel == null ? 0 : userTunnel.getId();
                String serviceName = forward.getId() + "_" + forward.getUserId() + "_" + userTunnelId;

                List<ChainTunnel> chainTunnels = chainTunnelService.list(new QueryWrapper<ChainTunnel>()
                        .eq("tunnel_id", forward.getTunnelId())
                        .eq("chain_type", 1));
                for (ChainTunnel chainTunnel : chainTunnels) {
                    GostUtil.PauseAndResumeService(chainTunnel.getNodeId(), serviceName, "PauseService");
                }

                forwardService.update(null, new UpdateWrapper<Forward>()
                        .eq("id", forward.getId())
                        .eq("status", 1)
                        .set("status", 0)
                        .set("updated_time", now));
                log.info("转发[ID: {}, 名称: {}]已到期并自动暂停", forward.getId(), forward.getName());
            } catch (Exception e) {
                log.error("暂停到期转发[ID: {}]失败", forward.getId(), e);
            }
        }
    }
}
