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.CoursePackage;
import com.reading.platform.mapper.CoursePackageMapper;
import com.reading.platform.service.CoursePackageService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 课程包服务实现类
 * 课程包是纯课程集合，不包含商业状态
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CoursePackageServiceImpl extends ServiceImpl<CoursePackageMapper, CoursePackage> implements CoursePackageService {

    private final CoursePackageMapper coursePackageMapper;

    @Override
    public Page<CoursePackage> getPackages(int pageNum, int pageSize, String keyword) {
        log.debug("查询课程包分页，页码：{}，每页大小：{}，关键词：{}", pageNum, pageSize, keyword);

        Page<CoursePackage> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<CoursePackage> wrapper = new LambdaQueryWrapper<>();

        if (keyword != null && !keyword.isEmpty()) {
            wrapper.like(CoursePackage::getName, keyword);
        }
        wrapper.orderByDesc(CoursePackage::getCreatedAt);

        Page<CoursePackage> result = coursePackageMapper.selectPage(page, wrapper);
        log.info("查询课程包分页成功，共{}条", result.getTotal());
        return result;
    }

    @Override
    public CoursePackage getPackageById(String id) {
        log.debug("查询课程包，ID: {}", id);

        CoursePackage pkg = coursePackageMapper.selectById(id);
        if (pkg == null) {
            log.warn("课程包不存在，ID: {}", id);
            throw new BusinessException(ErrorCode.DATA_NOT_FOUND, "课程包不存在");
        }
        log.info("查询课程包成功，名称：{}", pkg.getName());
        return pkg;
    }

    @Override
    public CoursePackage createPackage(CoursePackage pkg) {
        log.info("开始创建课程包，名称：{}", pkg.getName());

        coursePackageMapper.insert(pkg);
        log.info("课程包创建成功，ID: {}", pkg.getId());
        return pkg;
    }

    @Override
    public CoursePackage updatePackage(String id, CoursePackage pkg) {
        log.info("开始更新课程包，ID: {}", id);

        getPackageById(id);
        pkg.setId(id);
        coursePackageMapper.updateById(pkg);

        log.info("课程包更新成功，ID: {}", id);
        return coursePackageMapper.selectById(id);
    }

    @Override
    public void deletePackage(String id) {
        log.info("开始删除课程包，ID: {}", id);

        getPackageById(id);
        coursePackageMapper.deleteById(id);

        log.info("课程包删除成功，ID: {}", id);
    }

    // 注意：CoursePackage 不再包含状态字段，状态管理已移至 ProductBundle
    // 以下方法已废弃，请使用 ProductBundle 相关方法
}
