package com.zhentao.schedule;

import com.zhentao.entity.MatchData;
import com.zhentao.redis.RedisMatchPool;
import com.zhentao.redis.RedisMatchQueue;
import com.zhentao.service.MatchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
@EnableScheduling
public class MatchScheduler {
    private final MatchService matchService;
    private final RedisMatchQueue matchQueue;
    private final RedisMatchPool redisMatchPool;

    public MatchScheduler(MatchService matchService, RedisMatchQueue matchQueue, RedisMatchPool redisMatchPool) {
        this.matchService = matchService;
        this.matchQueue = matchQueue;
        this.redisMatchPool = redisMatchPool;
    }

    @Scheduled(fixedRate = 1000)
    public void scheduleMatching() {
        long q = matchQueue.getQueueSize();
        if (q <= 1) return;
        int batch = (int) Math.min(20, q);
        List<String> users = matchQueue.getTopPriorityUsers(batch);
        for (String uid : users) {
            if (!redisMatchPool.isUserInPool(uid)) { matchQueue.removeFromQueue(uid); continue; }
            MatchData data = redisMatchPool.getUserMatchData(uid);
            if (data == null) { matchQueue.removeFromQueue(uid); continue; }
            MatchService.MatchResult r = matchService.tryMatch(uid, data);
            if (r.isMatched()) {
                matchService.createMatch(uid, r.getMatchedUserId(), r.getMatchScore());
            } else {
                matchQueue.increaseUserPriority(uid, 5);
            }
        }
    }
}

