package com.reading.platform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.reading.platform.common.enums.ErrorCode;
import com.reading.platform.common.exception.BusinessException;
import com.reading.platform.entity.SchoolCourse;
import com.reading.platform.mapper.SchoolCourseMapper;
import com.reading.platform.service.SchoolCourseService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * 校本课程服务实现类
 */
@Service
@RequiredArgsConstructor
public class SchoolCourseServiceImpl extends ServiceImpl<SchoolCourseMapper, SchoolCourse> implements SchoolCourseService {

    private final SchoolCourseMapper schoolCourseMapper;

    @Override
    public Page<SchoolCourse> getCourses(int pageNum, int pageSize, String tenantId, String keyword) {
        Page<SchoolCourse> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<SchoolCourse> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SchoolCourse::getTenantId, tenantId);
        if (keyword != null && !keyword.isEmpty()) {
            wrapper.like(SchoolCourse::getName, keyword);
        }
        wrapper.orderByDesc(SchoolCourse::getCreatedAt);
        return schoolCourseMapper.selectPage(page, wrapper);
    }

    @Override
    public SchoolCourse getCourseById(String id) {
        SchoolCourse course = schoolCourseMapper.selectById(id);
        if (course == null) {
            throw new BusinessException(ErrorCode.DATA_NOT_FOUND, "School course not found");
        }
        return course;
    }

    @Override
    public SchoolCourse createCourse(String tenantId, String userId, SchoolCourse course) {
        course.setTenantId(tenantId);
        course.setCreatedBy(userId);
        schoolCourseMapper.insert(course);
        return course;
    }

    @Override
    public SchoolCourse updateCourse(String id, SchoolCourse course) {
        SchoolCourse existing = getCourseById(id);
        course.setId(id);
        course.setTenantId(existing.getTenantId());
        schoolCourseMapper.updateById(course);
        return schoolCourseMapper.selectById(id);
    }

    @Override
    public void deleteCourse(String id) {
        schoolCourseMapper.deleteById(id);
    }
}
