package com.zhentao.controller;

import com.zhentao.entity.MatchData;
import com.zhentao.service.MatchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/match")
public class MatchController {
    
    private final MatchService matchService;
    
    public MatchController(MatchService matchService) {
        this.matchService = matchService;
    }
    
    @PostMapping("/start")
    public Map<String, Object> startMatch(@RequestBody MatchData matchData) {
        log.info("收到匹配请求: userId={}", matchData.getUserId());
        
        try {
            if (matchData.getUserId() == null || matchData.getUserId().trim().isEmpty()) {
                return error("用户ID不能为空");
            }
            
            return matchService.handleMatchRequest(matchData);
        } catch (Exception e) {
            log.error("匹配请求处理失败", e);
            return error("匹配失败：" + e.getMessage());
        }
    }
    
    @PostMapping("/cancel")
    public Map<String, Object> cancelMatch(@RequestParam("userId") String userId) {
        log.info("收到取消匹配请求: userId={}", userId);
        
        try {
            boolean success = matchService.removeFromMatchPool(userId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("msg", success ? "取消匹配成功" : "您不在匹配队列中");
            response.put("data", null);
            
            return response;
        } catch (Exception e) {
            log.error("取消匹配失败", e);
            return error("取消匹配失败：" + e.getMessage());
        }
    }
    
    @GetMapping("/health")
    public Map<String, Object> health() {
        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("msg", "匹配服务运行正常");
        response.put("data", new HashMap<String, Object>() {{
            put("service", "match");
            put("status", "running");
            put("timestamp", System.currentTimeMillis());
        }});
        return response;
    }
    
    private Map<String, Object> error(String message) {
        Map<String, Object> response = new HashMap<>();
        response.put("code", 500);
        response.put("msg", message);
        response.put("data", null);
        return response;
    }
}

