package com.cyksj.service.sora.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.mapper.SoraCodeMapper;
import com.cyksj.model.entity.SoraCode;
import com.cyksj.model.request.SoraCodeAddReq;
import com.cyksj.model.request.SoraCodeUpdateReq;
import com.cyksj.service.sora.SoraCodeService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

/**
 * Sora邀请码Service实现类
 *
 * @author system
 * @date 2025-10-13
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SoraCodeServiceImpl implements SoraCodeService {

    private final SoraCodeMapper soraCodeMapper;

    @Override
    public void addSoraCode(SoraCodeAddReq req) {
        // 检查邀请码是否已存在
        Integer count = soraCodeMapper.selectCount(
            new LambdaQueryWrapper<SoraCode>()
                .eq(SoraCode::getCode, req.getCode())
        );
        if (count > 0) {
            throw new BusinessRuntimeException("邀请码已存在");
        }

        SoraCode soraCode = new SoraCode();
        soraCode.setCode(req.getCode());

        try {
            soraCodeMapper.insert(soraCode);
        } catch (DataAccessException e) {

        }
    }

    @Override
    public void updateSoraCode(SoraCodeUpdateReq req) {
        SoraCode soraCode = soraCodeMapper.selectById(req.getId());
        if (soraCode == null) {
            throw new BusinessRuntimeException("Sora邀请码不存在");
        }

        // 如果要更新邀请码，检查新邀请码是否已存在
        if (StrUtil.isNotBlank(req.getCode()) && !req.getCode().equals(soraCode.getCode())) {
            Integer count = soraCodeMapper.selectCount(
                new LambdaQueryWrapper<SoraCode>()
                    .eq(SoraCode::getCode, req.getCode())
                    .ne(SoraCode::getId, req.getId())
            );
            if (count > 0) {
                throw new BusinessRuntimeException("邀请码已存在");
            }
        }

        SoraCode updateSoraCode = new SoraCode();
        updateSoraCode.setId(req.getId());

        if (StrUtil.isNotBlank(req.getCode())) {
            updateSoraCode.setCode(req.getCode());
        }

        soraCodeMapper.updateById(updateSoraCode);
    }

    @Override
    public void deleteSoraCode(Long id) {
        SoraCode soraCode = soraCodeMapper.selectById(id);
        if (soraCode == null) {
            throw new BusinessRuntimeException("Sora邀请码不存在");
        }
        if (soraCode.getStatus()) {
            throw BusinessRuntimeException.getInstance("Sora邀请码已使用，不可删除");
        }
        soraCodeMapper.deleteById(id);
    }
}