package com.backendsys.modules.ai.volcengine.service.impl;

import com.backendsys.exception.CustException;
import com.backendsys.modules.ai.volcengine.dao.VolcengineVideoCollectDao;
import com.backendsys.modules.ai.volcengine.dao.VolcengineVideoTaskDetailDao;
import com.backendsys.modules.ai.volcengine.entity.VolcengineVideoCollect;
import com.backendsys.modules.ai.volcengine.entity.VolcengineVideoTaskDetail;
import com.backendsys.modules.ai.volcengine.service.VolcengineVideoCollectService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class VolcengineVideoCollectServiceImpl extends ServiceImpl<VolcengineVideoCollectDao, VolcengineVideoCollect> implements VolcengineVideoCollectService {

    @Autowired
    private VolcengineVideoTaskDetailDao volcengineVideoTaskDetailDao;

    @Override
    public boolean setCollect(VolcengineVideoCollect volcengineVideoCollect) {

        // 是否收藏 (-1取消收藏, 1加入收藏)
        Integer isCollect = volcengineVideoCollect.getIs_collect();
        Long taskDetailId = volcengineVideoCollect.getTask_detail_id();

        // 查询当前用户，是否已经收藏过该风格
        LambdaQueryWrapper<VolcengineVideoCollect> wrapperCollect = new LambdaQueryWrapper<>();
        wrapperCollect.eq(VolcengineVideoCollect::getUser_id, volcengineVideoCollect.getUser_id());
        wrapperCollect.eq(VolcengineVideoCollect::getTask_detail_id, taskDetailId);

        if (isCollect == 1) {
            // 如果已经收藏过，则不变
            VolcengineVideoCollect detail = baseMapper.selectOne(wrapperCollect);
            if (detail == null) {

                // [DB] 判断任务是否存在
                VolcengineVideoTaskDetail taskDetail = volcengineVideoTaskDetailDao.selectOne(Wrappers.<VolcengineVideoTaskDetail>lambdaQuery().eq(VolcengineVideoTaskDetail::getId, taskDetailId));
                if (taskDetail == null) {
                    throw new CustException("视频不存在");
                }
                volcengineVideoCollect.setTask_id(taskDetail.getTask_id());

                // [DB] 加入收藏
                baseMapper.insert(volcengineVideoCollect);
            }
        } else {
            // [DB] 取消收藏
            baseMapper.delete(wrapperCollect);
        }

        return true;
    }

}
