package com.datacenter.service.impl;

import com.datacenter.job.vo.FollowerCleanupCandidateVo;
import com.datacenter.mapper.FollowerCleanupMapper;
import com.datacenter.service.FollowerCleanupService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class FollowerCleanupServiceImpl implements FollowerCleanupService {

    private final FollowerCleanupMapper mapper;

    @Override
    public int checkAndRemoveFollowers() {
        List<FollowerCleanupCandidateVo> candidates = mapper.findCandidates();
        if (candidates.isEmpty()) {
            log.debug("跟单员清理：本次无需移除的跟单员");
            return 0;
        }
        log.info("跟单员清理：查询到候选记录 {} 条", candidates.size());

        int removed = 0;
        for (FollowerCleanupCandidateVo c : candidates) {
            try {
                removeOne(c);
                removed++;
                log.info("跟单员清理成功：followId={} customerId={} traderId={}",
                        c.getFollowId(), c.getCustomerId(), c.getTraderId());
            } catch (Exception e) {
                log.error("跟单员清理异常：followId={} customerId={} traderId={}",
                        c.getFollowId(), c.getCustomerId(), c.getTraderId(), e);
            }
        }
        return removed;
    }

    @Transactional(rollbackFor = Exception.class)
    public void removeOne(FollowerCleanupCandidateVo c) {
        // ① 先删交易对（依赖 risk_control.id），再删风控，最后更新跟随状态
        mapper.deleteFollowSymbols(c.getFollowId());
        mapper.deleteRiskControl(c.getFollowId());
        mapper.removeFollow(c.getFollowId());
    }
}
