package rd.controller.course;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.stp.StpUtil;
import rd.data.dto.course.CourseDTO;
import rd.data.db.table.Course;
import rd.data.model.response.Response;
import rd.service.activity.ActivityService;
import rd.service.activity.ActivityTargetService;
import rd.service.course.CourseService;
import rd.service.user.StudentUserService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/student/course")
public class StudentCourseController {
    private final CourseService courseService;
    private final ActivityTargetService activityTargetService;
    private final StudentUserService studentUserService;
    private final ActivityService activityService;

    public StudentCourseController(CourseService courseService,
                                   ActivityTargetService activityTargetService,
                                   StudentUserService studentUserService,
                                   ActivityService activityService) {
        this.courseService = courseService;
        this.activityTargetService = activityTargetService;
        this.studentUserService = studentUserService;
        this.activityService = activityService;
    }

    @SaCheckLogin
    @SaCheckRole("STUDENT")
    @GetMapping("/candidate")
    public Response<List<CourseDTO>> listCandidate(@RequestParam(value = "act", required = false) Long activityId) {
        Long uid = StpUtil.getLoginIdAsLong();
        var studentInfo = studentUserService.getInfoById(uid);

        if (activityId == null) {
            var currentActivity = activityService.getCurrentActivity();
            if (currentActivity == null) {
                return Response.success(new ArrayList<>());
            }

            activityId = currentActivity.getId();
        }

        var courseIdList = activityTargetService.getMajorGradeActivityCandidateCourses(
                studentInfo.major(), studentInfo.grade(), activityId
        );

        var courseIdMap = courseService.getCourse(courseIdList);
        var courseList = courseIdMap.values().stream()
                .map(this::convertCourse)
                .toList();

        return Response.success(courseList);
    }

    private CourseDTO convertCourse(Course course) {
        CourseDTO courseDTO = new CourseDTO();
        courseDTO.setId(course.getId());
        courseDTO.setName(course.getName());
        courseDTO.setCourseHours(course.getCourseHours());
        courseDTO.setSpringTerm(course.getSpringTerm());

        return courseDTO;
    }
}
