package org.cmh.backend.CourseManagement.controller;

import org.cmh.backend.CourseManagement.dto.GetCourseListResponse;
import org.cmh.backend.CourseManagement.dto.MessageResponse;
import org.cmh.backend.CourseManagement.dto.CourseRequest;
import org.cmh.backend.CourseManagement.dto.SearchCourseRequest;
import org.cmh.backend.CourseManagement.model.Course;
import org.cmh.backend.CourseManagement.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import jakarta.persistence.EntityNotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@RestController
@RequestMapping("/courses")
public class CourseController {

    private static final Logger logger = LoggerFactory.getLogger(CourseController.class);

    @Autowired
    private CourseService courseService;

    @GetMapping
    public ResponseEntity<GetCourseListResponse> getCoursesByRange(@RequestParam Integer start, @RequestParam Integer end, @RequestParam String token) {
        if (start >= end) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
        long courseCount = courseService.getCourseCount();
        return new ResponseEntity<>(new GetCourseListResponse(courseCount, courseService.getCoursesByRange(start, end)), HttpStatus.OK);
    }

    @GetMapping("/{id}")
    public ResponseEntity<Course> getCoursePage(@PathVariable Long id, @RequestParam String token) {
        try {
            return new ResponseEntity<>(courseService.getCourseById(id), HttpStatus.OK);
        } catch (EntityNotFoundException e) {
            logger.error("Course not found with id: {}", id, e);
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }

    @PostMapping
    public ResponseEntity<MessageResponse> createCourse(@RequestBody CourseRequest request) {
        try {
            courseService.createCourse(request);
        } catch (DataIntegrityViolationException e) {
            logger.error("Create course failed: Data integrity violation", e);
            return new ResponseEntity<>(new MessageResponse("创建失败，课程已存在或缺少字段"), HttpStatus.BAD_REQUEST);
        } catch (Exception e) {
            logger.error("Create course failed: {}", e.getMessage(), e);
            return new ResponseEntity<>(new MessageResponse("创建失败:" + e.getMessage()), HttpStatus.BAD_REQUEST);
        }
        return new ResponseEntity<>(new MessageResponse("创建成功"), HttpStatus.CREATED);
    }

    @PutMapping("/{id}")
    public ResponseEntity<MessageResponse> updateCourse(@PathVariable Long id, @RequestBody CourseRequest request) {
        try {
            courseService.updateCourse(id, request);
        } catch (DataIntegrityViolationException e) {
            logger.error("Update course failed: Data integrity violation", e);
            return new ResponseEntity<>(new MessageResponse("修改失败，新标题已存在或缺少字段"), HttpStatus.BAD_REQUEST);
        } catch (EntityNotFoundException e) {
            logger.error("Course not found with id: {}", id, e);
            return new ResponseEntity<>(new MessageResponse("修改失败: 课程不存在"), HttpStatus.NOT_FOUND);
        } catch (Exception e) {
            logger.error("Update course failed: {}", e.getMessage(), e);
            return new ResponseEntity<>(new MessageResponse("修改失败:" + e.getMessage()), HttpStatus.BAD_REQUEST);
        }
        return new ResponseEntity<>(new MessageResponse("修改成功"), HttpStatus.OK);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<MessageResponse> deleteCourse(@PathVariable Long id, @RequestParam String token) {
        try {
            courseService.deleteCourse(id);
        } catch (EntityNotFoundException e) {
            logger.error("Course not found with id: {}", id, e);
            return new ResponseEntity<>(new MessageResponse("删除失败，课程不存在"), HttpStatus.BAD_REQUEST);
        } catch (Exception e) {
            logger.error("Delete course failed: {}", e.getMessage(), e);
            return new ResponseEntity<>(new MessageResponse("删除失败:" + e.getMessage()), HttpStatus.BAD_REQUEST);
        }
        return new ResponseEntity<>(new MessageResponse("删除成功"), HttpStatus.OK);
    }

    @GetMapping("/search")
    public ResponseEntity<GetCourseListResponse> searchCourses(@RequestParam String token,
                                                               @RequestParam(required = false) String title,
                                                               @RequestParam(required = false) String author,
                                                               @RequestParam(required = false) String description,
                                                               @RequestParam(required = false) String sortOrder,
                                                               @RequestParam Integer start,
                                                               @RequestParam Integer end) {
        if (start >= end) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }

        try {
            SearchCourseRequest request = new SearchCourseRequest(token, title, author, description, sortOrder, start, end);
            List<Course> courses = courseService.searchCourses(request);
            long courseCount = courseService.getCourseCountByCriteria(title, author, description, sortOrder);

            return new ResponseEntity<>(new GetCourseListResponse(courseCount, courses), HttpStatus.OK);
        } catch (Exception e) {
            logger.error("Search courses failed with parameters: title={}, author={}, description={}, sortOrder={}, start={}, end={}",
                    title, author, description, sortOrder, start, end, e);
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    @GetMapping("/sort")
    public ResponseEntity<GetCourseListResponse> sortCourses(@RequestParam String token,
                                                             @RequestParam String sortField,
                                                             @RequestParam String sortDirection,
                                                             @RequestParam Integer start,
                                                             @RequestParam Integer end) {
        if (start >= end) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }

        try {
            long courseCount = courseService.getCourseCount();
            List<Course> sortedCourses = courseService.sortCourses(sortField, sortDirection, start, end);

            return new ResponseEntity<>(new GetCourseListResponse(courseCount, sortedCourses), HttpStatus.OK);
        } catch (Exception e) {
            logger.error("Sort courses failed with parameters: sortField={}, sortDirection={}, start={}, end={}",
                    sortField, sortDirection, start, end, e);
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}