package com.reading.platform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.reading.platform.common.enums.ErrorCode;
import com.reading.platform.common.exception.BusinessException;
import com.reading.platform.entity.CourseLesson;
import com.reading.platform.mapper.CourseLessonMapper;
import com.reading.platform.service.CourseLessonService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 课程课时服务实现类
 */
@Service
@RequiredArgsConstructor
public class CourseLessonServiceImpl implements CourseLessonService {

    private final CourseLessonMapper courseLessonMapper;

    @Override
    public List<CourseLesson> getLessonsByCourse(String courseId) {
        LambdaQueryWrapper<CourseLesson> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CourseLesson::getCourseId, courseId)
               .orderByAsc(CourseLesson::getSortOrder);
        return courseLessonMapper.selectList(wrapper);
    }

    @Override
    public CourseLesson getLessonById(String id) {
        CourseLesson lesson = courseLessonMapper.selectById(id);
        if (lesson == null) {
            throw new BusinessException(ErrorCode.DATA_NOT_FOUND, "Course lesson not found");
        }
        return lesson;
    }

    @Override
    public CourseLesson createLesson(CourseLesson lesson) {
        courseLessonMapper.insert(lesson);
        return lesson;
    }

    @Override
    public CourseLesson updateLesson(String id, CourseLesson lesson) {
        getLessonById(id);
        lesson.setId(id);
        courseLessonMapper.updateById(lesson);
        return courseLessonMapper.selectById(id);
    }

    @Override
    public void deleteLesson(String id) {
        courseLessonMapper.deleteById(id);
    }
}
