package com.dora.controller;

import com.dora.entity.Course;
import com.dora.mapper.CourseMapper;
import com.dora.util.CoursePermissionUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

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

/**
 * 调试接口控制器
 * 用于调试和验证系统中的数据一致性问题
 */
@Tag(name = "调试接口", description = "用于调试和验证数据一致性的接口")
@RestController
@RequestMapping("/debug")
@RequiredArgsConstructor
@Slf4j
public class DebugController {

    private final CourseMapper courseMapper;
    
    // 常量定义
    private static final String ERROR_KEY = "error";
    private static final String LEVEL_KEY = "level";
    private static final String IS_FREE_KEY = "isFree";

    @Operation(summary = "验证课程权限一致性", description = "检查指定课程的权限配置是否一致")
    @GetMapping("/course/permission/{courseId}")
    public Map<String, Object> validateCoursePermission(@PathVariable Long courseId) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 获取课程信息
            Course course = courseMapper.selectById(courseId);
            if (course == null) {
                result.put(ERROR_KEY, "课程不存在: " + courseId);
                return result;
            }
            
            // 基本课程信息
            result.put("courseId", course.getId());
            result.put("title", course.getTitle());
            result.put(LEVEL_KEY, course.getLevel());
            result.put(IS_FREE_KEY, course.getIsFree());
            result.put("auditStatus", course.getAuditStatus());
            
            // 权限计算结果
            String calculatedVipType = CoursePermissionUtil.getVipType(course.getLevel());
            String roleName = CoursePermissionUtil.getRoleNameByLevel(course.getLevel());
            boolean isFreeFlag = course.getIsFree() != null && course.getIsFree() == 1;
            
            result.put("calculatedVipType", calculatedVipType);
            result.put("roleName", roleName);
            result.put("isFreeFlag", isFreeFlag);
            
            // 验证一致性
            boolean isConsistent = CoursePermissionUtil.validatePermissionConsistency(
                course.getLevel(), isFreeFlag, calculatedVipType);
            result.put("isConsistent", isConsistent);
            
            // 权限检查示例
            Map<String, Object> permissionTests = new HashMap<>();
            for (int userLevel = 0; userLevel <= 3; userLevel++) {
                boolean hasPermission = CoursePermissionUtil.hasPermission(userLevel, course.getLevel());
                String reason = hasPermission ? "有权限" : 
                    CoursePermissionUtil.getAccessDeniedReason(userLevel, course.getLevel());
                
                permissionTests.put("用户级别" + userLevel + "(" + 
                    CoursePermissionUtil.getRoleNameByLevel(userLevel) + ")", 
                    Map.of("hasPermission", hasPermission, "reason", reason));
            }
            result.put("permissionTests", permissionTests);
            
            log.info("课程权限验证完成: courseId={}, level={}, vipType={}, consistent={}", 
                    courseId, course.getLevel(), calculatedVipType, isConsistent);
            
        } catch (Exception e) {
            log.error("验证课程权限失败: courseId={}", courseId, e);
            result.put(ERROR_KEY, "验证失败: " + e.getMessage());
        }
        
        return result;
    }

    @Operation(summary = "对比两个接口的课程数据", description = "对比热门课程和搜索接口返回的相同课程数据")
    @GetMapping("/course/compare")
    public Map<String, Object> compareCourseData(@RequestParam(required = false) String keyword) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 获取热门课程数据
            List<Course> hotCourses = courseMapper.selectHotCourses(0, 50);
            
            // 获取搜索课程数据
            Map<String, Object> searchParams = new HashMap<>();
            if (keyword != null && !keyword.trim().isEmpty()) {
                searchParams.put("keyword", keyword.trim());
            }
            searchParams.put("offset", 0);
            searchParams.put("limit", 50);
            List<Course> searchCourses = courseMapper.searchCourses(searchParams);
            
            // 对比结果
            result.put("hotCoursesCount", hotCourses.size());
            result.put("searchCoursesCount", searchCourses.size());
            
            // 找出共同课程并对比权限信息
            Map<Long, Map<String, Object>> commonCourses = new HashMap<>();
            for (Course hotCourse : hotCourses) {
                Course matchedSearchCourse = searchCourses.stream()
                    .filter(sc -> sc.getId().equals(hotCourse.getId()))
                    .findFirst()
                    .orElse(null);
                
                if (matchedSearchCourse != null) {
                    Map<String, Object> comparison = new HashMap<>();
                    
                    // 热门接口数据
                    Map<String, Object> hotData = Map.of(
                        LEVEL_KEY, hotCourse.getLevel(),
                        IS_FREE_KEY, hotCourse.getIsFree(),
                        "vipType", CoursePermissionUtil.getVipType(hotCourse.getLevel())
                    );
                    
                    // 搜索接口数据
                    Map<String, Object> searchData = Map.of(
                        LEVEL_KEY, matchedSearchCourse.getLevel(),
                        IS_FREE_KEY, matchedSearchCourse.getIsFree(),
                        "vipType", CoursePermissionUtil.getVipType(matchedSearchCourse.getLevel())
                    );
                    
                    // 检查是否一致
                    boolean isConsistent = hotCourse.getLevel().equals(matchedSearchCourse.getLevel()) &&
                                         hotCourse.getIsFree().equals(matchedSearchCourse.getIsFree());
                    
                    comparison.put("title", hotCourse.getTitle());
                    comparison.put("hotData", hotData);
                    comparison.put("searchData", searchData);
                    comparison.put("isConsistent", isConsistent);
                    
                    commonCourses.put(hotCourse.getId(), comparison);
                }
            }
            
            result.put("commonCoursesCount", commonCourses.size());
            result.put("commonCourses", commonCourses);
            
            log.info("课程数据对比完成: 热门课程数={}, 搜索课程数={}, 共同课程数={}", 
                    hotCourses.size(), searchCourses.size(), commonCourses.size());
            
        } catch (Exception e) {
            log.error("对比课程数据失败", e);
            result.put(ERROR_KEY, "对比失败: " + e.getMessage());
        }
        
        return result;
    }
}
