package rd.controller.schedule;

import cn.dev33.satoken.annotation.SaCheckRole;
import rd.data.dto.schedule.CourseScheduleDTO;
import rd.data.db.table.CourseSchedule;
import rd.data.model.request.schedule.CourseScheduleRequest;
import rd.data.model.response.Response;
import rd.service.schedule.CourseScheduleService;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/admin/course-schedule")
public class AdminScheduleController {

    private final CourseScheduleService courseScheduleService;

    public AdminScheduleController(CourseScheduleService courseScheduleService) {
        this.courseScheduleService = courseScheduleService;
    }

    @SaCheckRole("ADMIN")
    @PostMapping("/add")
    public Response<CourseSchedule> add(@RequestParam("course") Long courseId,
                                        @RequestBody CourseScheduleRequest request) {
        var newCourse = courseScheduleService.add(courseId, convert(request));

        return Response.success(newCourse);
    }

    @SaCheckRole("ADMIN")
    @RequestMapping("/clone")
    public Response<Object> clone(@RequestParam("course") Long course,
                                 @RequestParam("from") String sourceTerm,
                                 @RequestParam("to") String targetTerm) {
        courseScheduleService.cloneSchedule(course, sourceTerm, targetTerm);
        return Response.success();
    }

    @SaCheckRole("ADMIN")
    @PostMapping("/update")
    public Response<CourseSchedule> update(@RequestParam("id") Long id, @RequestBody CourseScheduleRequest request) {
        var dto = convert(request);

        var newCourse = courseScheduleService.update(id, dto);

        return Response.success(newCourse);
    }

    private CourseScheduleDTO convert(CourseScheduleRequest request) {
        CourseScheduleDTO dto = new CourseScheduleDTO();
        dto.setStartWeek(request.getStartWeek());
        dto.setEndWeek(request.getEndWeek());
        dto.setTime(request.getEndWeek());
        dto.setWeekday(request.getWeekday());
        dto.setAcademicTerm(request.getTerm());
        dto.setPlace(request.getPlace());
        dto.setTime(request.getSection());

        return dto;
    }

    @SaCheckRole("ADMIN")
    @PostMapping("/delete")
    public Response<Object> delete(@RequestParam("id") Long id) {
        courseScheduleService.delete(id);
        return Response.success();
    }
}
