package com.reading.platform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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 org.springframework.stereotype.Service;

/**
 * 课程包服务实现类
 */
@Service
@RequiredArgsConstructor
public class CoursePackageServiceImpl implements CoursePackageService {

    private final CoursePackageMapper coursePackageMapper;

    @Override
    public Page<CoursePackage> getPackages(int pageNum, int pageSize, String keyword, String status) {
        Page<CoursePackage> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<CoursePackage> wrapper = new LambdaQueryWrapper<>();
        if (keyword != null && !keyword.isEmpty()) {
            wrapper.like(CoursePackage::getName, keyword);
        }
        if (status != null && !status.isEmpty()) {
            wrapper.eq(CoursePackage::getStatus, status);
        }
        wrapper.orderByDesc(CoursePackage::getCreatedAt);
        return coursePackageMapper.selectPage(page, wrapper);
    }

    @Override
    public CoursePackage getPackageById(String id) {
        CoursePackage pkg = coursePackageMapper.selectById(id);
        if (pkg == null) {
            throw new BusinessException(ErrorCode.DATA_NOT_FOUND, "Course package not found");
        }
        return pkg;
    }

    @Override
    public CoursePackage createPackage(CoursePackage pkg) {
        coursePackageMapper.insert(pkg);
        return pkg;
    }

    @Override
    public CoursePackage updatePackage(String id, CoursePackage pkg) {
        getPackageById(id);
        pkg.setId(id);
        coursePackageMapper.updateById(pkg);
        return coursePackageMapper.selectById(id);
    }

    @Override
    public void deletePackage(String id) {
        coursePackageMapper.deleteById(id);
    }

    @Override
    public void submitPackage(String id) {
        CoursePackage pkg = getPackageById(id);
        pkg.setStatus("pending");
        coursePackageMapper.updateById(pkg);
    }

    @Override
    public void reviewPackage(String id, boolean approved, String comment) {
        CoursePackage pkg = getPackageById(id);
        pkg.setStatus(approved ? "published" : "rejected");
        coursePackageMapper.updateById(pkg);
    }

    @Override
    public void publishPackage(String id) {
        CoursePackage pkg = getPackageById(id);
        pkg.setStatus("published");
        coursePackageMapper.updateById(pkg);
    }

    @Override
    public void offlinePackage(String id) {
        CoursePackage pkg = getPackageById(id);
        pkg.setStatus("archived");
        coursePackageMapper.updateById(pkg);
    }
}
