package com.reading.platform.controller.teacher;

import com.reading.platform.common.response.PageResult;
import com.reading.platform.common.response.Result;
import com.reading.platform.common.security.SecurityUtils;
import com.reading.platform.dto.response.ClassInfoResponse;
import com.reading.platform.dto.response.StudentInfoResponse;
import com.reading.platform.dto.response.TeacherInfoResponse;
import com.reading.platform.entity.Course;
import com.reading.platform.entity.Student;
import com.reading.platform.service.ClassService;
import com.reading.platform.service.CourseService;
import com.reading.platform.service.StudentService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

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

@Tag(name = "教师 - 课程", description = "课程接口（教师专用）")
@RestController
@RequestMapping("/api/v1/teacher/courses")
@RequiredArgsConstructor
public class TeacherCourseController {

    private final CourseService courseService;
    private final ClassService classService;
    private final StudentService studentService;

    @Operation(summary = "根据 ID 获取课程")
    @GetMapping("/{id}")
    public Result<Course> getCourse(@PathVariable String id) {
        return Result.success(courseService.getCourseById(id));
    }

    @Operation(summary = "获取课程分页")
    @GetMapping
    public Result<PageResult<Course>> getCoursePage(
            @RequestParam(value = "page", required = false) Integer pageNum,
            @RequestParam(required = false) Integer pageSize,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String grade) {
        String tenantId = SecurityUtils.getCurrentTenantId();
        return Result.success(PageResult.of(courseService.getCoursePage(tenantId, pageNum, pageSize, keyword, null, "published")));
    }

    @Operation(summary = "获取所有课程")
    @GetMapping("/all")
    public Result<List<Course>> getAllCourses() {
        String tenantId = SecurityUtils.getCurrentTenantId();
        return Result.success(courseService.getCoursesByTenantId(tenantId));
    }

    @Operation(summary = "获取教师的班级列表")
    @GetMapping("/classes")
    public Result<List<ClassInfoResponse>> getTeacherClasses() {
        String tenantId = SecurityUtils.getCurrentTenantId();
        List<com.reading.platform.entity.Clazz> classes = classService.getClassList(tenantId);

        List<ClassInfoResponse> result = new ArrayList<>();
        for (com.reading.platform.entity.Clazz clazz : classes) {
            ClassInfoResponse response = new ClassInfoResponse();
            response.setId(clazz.getId());
            response.setName(clazz.getName());
            response.setGrade(clazz.getGrade());
            response.setStudentCount(0);
            response.setLessonCount(0);
            response.setMyRole("MAIN");
            response.setIsPrimary(true);
            result.add(response);
        }
        return Result.success(result);
    }

    @Operation(summary = "获取教师所有学生分页")
    @GetMapping("/students")
    public Result<PageResult<StudentInfoResponse>> getTeacherStudents(
            @RequestParam(value = "page", required = false) Integer pageNum,
            @RequestParam(required = false) Integer pageSize,
            @RequestParam(required = false) String keyword) {

        if (pageNum == null) pageNum = 1;
        if (pageSize == null) pageSize = 10;

        String tenantId = SecurityUtils.getCurrentTenantId();
        var page = studentService.getStudentPage(tenantId, pageNum, pageSize, keyword, null, null);

        List<StudentInfoResponse> result = new ArrayList<>();
        for (Student student : page.getRecords()) {
            StudentInfoResponse response = new StudentInfoResponse();
            response.setId(student.getId());
            response.setName(student.getName());
            response.setGender(student.getGender());
            response.setBirthDate(student.getBirthDate() != null ? student.getBirthDate().toString() : null);
            response.setClassId(student.getClassId());

            if (student.getClassId() != null) {
                var clazz = classService.getClassById(student.getClassId());
                if (clazz != null) {
                    StudentInfoResponse.ClassSimpleInfo classInfo = new StudentInfoResponse.ClassSimpleInfo();
                    classInfo.setId(clazz.getId());
                    classInfo.setName(clazz.getName());
                    classInfo.setGrade(clazz.getGrade());
                    response.setClassInfo(classInfo);
                }
            }

            response.setParentName(student.getParentName());
            response.setParentPhone(student.getParentPhone());
            response.setCreatedAt(student.getCreatedAt() != null ? student.getCreatedAt().toString() : null);
            result.add(response);
        }

        return Result.success(PageResult.of(result, page.getTotal(), page.getCurrent(), page.getSize()));
    }

    @Operation(summary = "获取班级学生分页")
    @GetMapping("/classes/{classId}/students")
    public Result<PageResult<StudentInfoResponse>> getClassStudents(
            @PathVariable String classId,
            @RequestParam(value = "page", required = false) Integer pageNum,
            @RequestParam(required = false) Integer pageSize,
            @RequestParam(required = false) String keyword) {

        var page = classService.getClassStudents(classId, pageNum, pageSize, keyword);

        List<StudentInfoResponse> result = new ArrayList<>();
        for (Student student : page.getRecords()) {
            StudentInfoResponse response = new StudentInfoResponse();
            response.setId(student.getId());
            response.setName(student.getName());
            response.setGender(student.getGender());
            response.setBirthDate(student.getBirthDate() != null ? student.getBirthDate().toString() : null);
            response.setParentName(student.getParentName());
            response.setParentPhone(student.getParentPhone());
            response.setLessonCount(student.getLessonCount() != null ? student.getLessonCount() : 0);
            response.setReadingCount(student.getReadingCount() != null ? student.getReadingCount() : 0);
            response.setCreatedAt(student.getCreatedAt() != null ? student.getCreatedAt().toString() : null);
            result.add(response);
        }

        return Result.success(PageResult.of(result, page.getTotal(), page.getCurrent(), page.getSize()));
    }

    @Operation(summary = "获取班级教师列表")
    @GetMapping("/classes/{classId}/teachers")
    public Result<List<TeacherInfoResponse>> getClassTeachers(@PathVariable String classId) {
        List<TeacherInfoResponse> result = classService.getClassTeachers(classId).stream().map(ct -> {
            TeacherInfoResponse response = new TeacherInfoResponse();
            response.setTeacherId(ct.getTeacherId());
            response.setRole(ct.getRole());
            response.setIsPrimary(ct.getIsPrimary());
            return response;
        }).toList();

        return Result.success(result);
    }

}
