package com.xindazhou.business.service.version;

import com.xindazhou.framework.common.pojo.PageResult;
import com.xindazhou.business.controller.admin.version.vo.VersionPageReqVO;
import com.xindazhou.business.controller.admin.version.vo.VersionSaveReqVO;
import com.xindazhou.business.convert.version.VersionConvert;
import com.xindazhou.business.dal.dataobject.version.VersionDO;
import com.xindazhou.business.dal.mysql.version.VersionMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.util.List;

import static com.xindazhou.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.xindazhou.business.enums.ErrorCodeConstants.*;

/**
 * 版本管理 Service 实现类
 *
 * @author xindazhou
 */
@Service
@Slf4j
@Validated
public class VersionServiceImpl implements VersionService {

    @Resource
    private VersionMapper versionMapper;

    @Override
    public Long createVersion(VersionSaveReqVO createReqVO) {
        // 插入版本
        VersionDO version = VersionConvert.INSTANCE.convert(createReqVO);
        versionMapper.insert(version);
        return version.getId();
    }

    @Override
    public void updateVersion(VersionSaveReqVO updateReqVO) {
        // 校验版本存在
        validateVersionExists(updateReqVO.getId());

        // 更新版本
        VersionDO updateObj = VersionConvert.INSTANCE.convert(updateReqVO);
        versionMapper.updateById(updateObj);
    }

    @Override
    public void deleteVersion(Long id) {
        // 校验版本存在
        validateVersionExists(id);
        // 删除
        versionMapper.deleteById(id);
    }

    @Override
    public void deleteVersionList(List<Long> ids) {
        // 批量删除
        versionMapper.deleteByIds(ids);
    }

    @Override
    public VersionDO getVersion(Long id) {
        return versionMapper.selectById(id);
    }

    @Override
    public PageResult<VersionDO> getVersionPage(VersionPageReqVO pageReqVO) {
        return versionMapper.selectPage(pageReqVO);
    }

    @Override
    public VersionDO getLatestVersion(Integer platform) {
        // 获取指定平台的最新版本（启用状态）
        // 如果没有版本，返回 null（前端会处理这种情况）
        return versionMapper.selectLatestByPlatform(platform);
    }

    @Override
    public void updateVersionStatus(Long id, Integer status) {
        // 校验版本存在
        validateVersionExists(id);
        // 更新状态
        VersionDO updateObj = new VersionDO();
        updateObj.setId(id);
        updateObj.setStatus(status);
        versionMapper.updateById(updateObj);
    }

    private VersionDO validateVersionExists(Long id) {
        VersionDO version = versionMapper.selectById(id);
        if (version == null) {
            throw exception(VERSION_NOT_EXISTS);
        }
        return version;
    }

}

