package com.lesingle.edu.controller.admin;

import com.lesingle.edu.common.annotation.Log;
import com.lesingle.edu.common.enums.LogModule;
import com.lesingle.edu.common.enums.LogOperationType;
import com.lesingle.edu.common.annotation.RequireRole;
import com.lesingle.edu.common.enums.UserRole;
import com.lesingle.edu.common.response.Result;
import com.lesingle.edu.dto.request.CourseLessonCreateRequest;
import com.lesingle.edu.dto.request.LessonStepCreateRequest;
import com.lesingle.edu.dto.response.CourseLessonResponse;
import com.lesingle.edu.dto.response.LessonStepResponse;
import com.lesingle.edu.entity.CourseLesson;
import com.lesingle.edu.entity.LessonStep;
import com.lesingle.edu.service.CourseLessonService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 课程环节控制器（超管端）
 */
@RestController
@RequestMapping("/api/v1/admin/courses")
@RequiredArgsConstructor
@Tag(name = "超管端 - 课程环节")
public class AdminCourseLessonController {

    private final CourseLessonService courseLessonService;

    @GetMapping("/{courseId}/lessons")
    @Operation(summary = "获取课程的所有环节")
    public Result<List<CourseLessonResponse>> findAll(@PathVariable Long courseId) {
        List<CourseLesson> lessons = courseLessonService.findByCourseId(courseId);
        List<CourseLessonResponse> responses = lessons.stream()
                .map(this::toLessonResponse)
                .collect(Collectors.toList());
        return Result.success(responses);
    }

    @GetMapping("/{courseId}/lessons/{id}")
    @Operation(summary = "获取课程环节详情")
    public Result<CourseLessonResponse> findOne(
            @PathVariable Long courseId,
            @PathVariable Long id) {
        CourseLesson lesson = courseLessonService.findById(id);
        return Result.success(toLessonResponse(lesson));
    }

    @GetMapping("/{courseId}/lessons/type/{lessonType}")
    @Operation(summary = "按类型获取课程环节")
    public Result<CourseLessonResponse> findByType(
            @PathVariable Long courseId,
            @PathVariable String lessonType) {
        CourseLesson lesson = courseLessonService.findByType(courseId, lessonType);
        if (lesson == null) {
            return Result.success(null);
        }
        return Result.success(toLessonResponse(lesson));
    }

    @PostMapping("/{courseId}/lessons")
    @Operation(summary = "创建课程环节")
    @Log(module = LogModule.COURSE_LESSON, type = LogOperationType.CREATE, description = "创建课程环节")
    @RequireRole(UserRole.ADMIN)
    public Result<CourseLessonResponse> create(
            @PathVariable Long courseId,
            @Valid @RequestBody CourseLessonCreateRequest request) {
        CourseLesson lesson = courseLessonService.create(
                courseId,
                request.getLessonType(),
                request.getName(),
                request.getDescription(),
                request.getDuration(),
                request.getVideoPath(),
                request.getVideoName(),
                request.getPptPath(),
                request.getPptName(),
                request.getPdfPath(),
                request.getPdfName(),
                request.getObjectives(),
                request.getPreparation(),
                request.getExtension(),
                request.getReflection(),
                request.getAssessmentData(),
                request.getUseTemplate()
        );
        return Result.success(toLessonResponse(lesson));
    }

    @PutMapping("/{courseId}/lessons/{id}")
    @Operation(summary = "更新课程环节")
    @Log(module = LogModule.COURSE_LESSON, type = LogOperationType.UPDATE, description = "更新课程环节")
    @RequireRole(UserRole.ADMIN)
    public Result<CourseLessonResponse> update(
            @PathVariable Long courseId,
            @PathVariable Long id,
            @RequestBody CourseLessonCreateRequest request) {
        CourseLesson lesson = courseLessonService.update(
                id,
                request.getName(),
                request.getDescription(),
                request.getDuration(),
                request.getVideoPath(),
                request.getVideoName(),
                request.getPptPath(),
                request.getPptName(),
                request.getPdfPath(),
                request.getPdfName(),
                request.getObjectives(),
                request.getPreparation(),
                request.getExtension(),
                request.getReflection(),
                request.getAssessmentData(),
                request.getUseTemplate()
        );
        return Result.success(toLessonResponse(lesson));
    }

    @DeleteMapping("/{courseId}/lessons/{id}")
    @Operation(summary = "删除课程环节")
    @Log(module = LogModule.COURSE_LESSON, type = LogOperationType.DELETE, description = "删除课程环节")
    @RequireRole(UserRole.ADMIN)
    public Result<Void> delete(
            @PathVariable Long courseId,
            @PathVariable Long id) {
        courseLessonService.delete(id);
        return Result.success();
    }

    @PutMapping("/{courseId}/lessons/reorder")
    @Operation(summary = "重新排序课程环节")
    @Log(module = LogModule.COURSE_LESSON, type = LogOperationType.UPDATE, description = "重新排序课程环节")
    @RequireRole(UserRole.ADMIN)
    public Result<Void> reorder(
            @PathVariable Long courseId,
            @RequestBody List<Long> lessonIds) {
        courseLessonService.reorder(courseId, lessonIds);
        return Result.success();
    }

    // ==================== 教学环节管理 ====================

    @GetMapping("/{courseId}/lessons/{lessonId}/steps")
    @Operation(summary = "获取课时的教学环节")
    public Result<List<LessonStepResponse>> findSteps(
            @PathVariable Long courseId,
            @PathVariable Long lessonId) {
        List<LessonStep> steps = courseLessonService.findSteps(lessonId);
        List<LessonStepResponse> responses = steps.stream()
                .map(this::toStepResponse)
                .collect(Collectors.toList());
        return Result.success(responses);
    }

    @PostMapping("/{courseId}/lessons/{lessonId}/steps")
    @Operation(summary = "创建教学环节")
    @Log(module = LogModule.COURSE_LESSON, type = LogOperationType.CREATE, description = "创建教学环节")
    @RequireRole(UserRole.ADMIN)
    public Result<LessonStepResponse> createStep(
            @PathVariable Long courseId,
            @PathVariable Long lessonId,
            @Valid @RequestBody LessonStepCreateRequest request) {
        LessonStep step = courseLessonService.createStep(
                lessonId,
                request.getName(),
                request.getContent(),
                request.getDuration(),
                request.getObjective(),
                request.getResourceIds()
        );
        return Result.success(toStepResponse(step));
    }

    @PutMapping("/{courseId}/lessons/steps/{stepId}")
    @Operation(summary = "更新教学环节")
    @Log(module = LogModule.COURSE_LESSON, type = LogOperationType.UPDATE, description = "更新教学环节")
    @RequireRole(UserRole.ADMIN)
    public Result<LessonStepResponse> updateStep(
            @PathVariable Long courseId,
            @PathVariable Long stepId,
            @Valid @RequestBody LessonStepCreateRequest request) {
        LessonStep step = courseLessonService.updateStep(
                stepId,
                request.getName(),
                request.getContent(),
                request.getDuration(),
                request.getObjective(),
                request.getResourceIds()
        );
        return Result.success(toStepResponse(step));
    }

    @DeleteMapping("/{courseId}/lessons/steps/{stepId}")
    @Operation(summary = "删除教学环节")
    @Log(module = LogModule.COURSE_LESSON, type = LogOperationType.DELETE, description = "删除教学环节")
    @RequireRole(UserRole.ADMIN)
    public Result<Void> removeStep(
            @PathVariable Long courseId,
            @PathVariable Long stepId) {
        courseLessonService.deleteStep(stepId);
        return Result.success();
    }

    @PutMapping("/{courseId}/lessons/{lessonId}/steps/reorder")
    @Operation(summary = "重新排序教学环节")
    @Log(module = LogModule.COURSE_LESSON, type = LogOperationType.UPDATE, description = "重新排序教学环节")
    @RequireRole(UserRole.ADMIN)
    public Result<Void> reorderSteps(
            @PathVariable Long courseId,
            @PathVariable Long lessonId,
            @RequestBody List<Long> stepIds) {
        courseLessonService.reorderSteps(lessonId, stepIds);
        return Result.success();
    }

    /**
     * 将 CourseLesson 实体转换为 CourseLessonResponse
     */
    private CourseLessonResponse toLessonResponse(CourseLesson lesson) {
        // 获取教学环节
        List<LessonStep> steps = courseLessonService.findSteps(lesson.getId());
        List<LessonStepResponse> stepResponses = steps.stream()
                .map(this::toStepResponse)
                .collect(Collectors.toList());

        return CourseLessonResponse.builder()
                .id(lesson.getId())
                .courseId(lesson.getCourseId())
                .lessonType(lesson.getLessonType())
                .name(lesson.getName())
                .description(lesson.getDescription())
                .duration(lesson.getDuration())
                .videoPath(lesson.getVideoPath())
                .videoName(lesson.getVideoName())
                .pptPath(lesson.getPptPath())
                .pptName(lesson.getPptName())
                .pdfPath(lesson.getPdfPath())
                .pdfName(lesson.getPdfName())
                .objectives(lesson.getObjectives())
                .preparation(lesson.getPreparation())
                .extension(lesson.getExtension())
                .reflection(lesson.getReflection())
                .assessmentData(lesson.getAssessmentData())
                .useTemplate(lesson.getUseTemplate())
                .sortOrder(lesson.getSortOrder())
                .steps(stepResponses)
                .createdAt(lesson.getCreatedAt())
                .updatedAt(lesson.getUpdatedAt())
                .build();
    }

    /**
     * 将 LessonStep 实体转换为 LessonStepResponse
     */
    private LessonStepResponse toStepResponse(LessonStep step) {
        return LessonStepResponse.builder()
                .id(step.getId())
                .lessonId(step.getLessonId())
                .name(step.getName())
                .content(step.getContent())
                .duration(step.getDuration())
                .objective(step.getObjective())
                .resourceIds(step.getResourceIds())
                .sortOrder(step.getSortOrder())
                .createdAt(step.getCreatedAt())
                .updatedAt(step.getUpdatedAt())
                .build();
    }
}