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

import com.backendsys.exception.CustException;
import com.backendsys.modules.ai.chat.dao.ChatDao;
import com.backendsys.modules.ai.chat.dao.ChatHistoryDao;
import com.backendsys.modules.ai.chat.entity.Chat;
import com.backendsys.modules.ai.chat.entity.ChatHistory;
import com.backendsys.modules.ai.chat.service.ChatHistoryService;
import com.backendsys.utils.response.PageEntity;
import com.backendsys.utils.response.PageInfoResult;
import com.backendsys.utils.v2.PageUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
public class ChatHistoryServiceImpl implements ChatHistoryService {

    @Autowired
    private ChatDao chatDao;

    @Autowired
    private ChatHistoryDao chatHistoryDao;

    /**
     * 获取我的对话历史列表
     */
    @Override
    public PageEntity selectChatHistoryList(ChatHistory history) {
        PageUtils.startPage();  // 分页
        List<ChatHistory> list = chatHistoryDao.selectChatHistoryList(history);
        return new PageInfoResult(list).toEntity();
    }

    /**
     * 删除我的对话历史 (软删除)
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> deleteChatHistory(ChatHistory chatHistory) {

        String history_code = chatHistory.getHistory_code();

        ChatHistory chatHistoryDetail = chatHistoryDao.selectOne(new LambdaQueryWrapper<ChatHistory>()
                .eq(ChatHistory::getDel_flag, -1)
                .eq(ChatHistory::getHistory_code, history_code));
        if (chatHistoryDetail == null) throw new CustException("history_code 不存在");
        chatHistoryDetail.setDel_flag(1);
        // [软删除] 删除对话记录
        chatHistoryDao.updateById(chatHistoryDetail);

        List<Chat> chatList = chatDao.selectList(new LambdaQueryWrapper<Chat>()
            .eq(Chat::getDel_flag, -1)
            .eq(Chat::getHistory_code, history_code));
        if (chatList != null && !chatList.isEmpty()) {
            chatList.stream().forEach(chat -> {
                // [软删除] 删除对话
                chat.setDel_flag(1);
                chatDao.updateById(chat);
            });
        }

//        // 删除对话记录
//        chatHistoryDao.delete(new LambdaQueryWrapper<ChatHistory>().eq(ChatHistory::getHistory_code, history_code));

//        // 删除对话
//        chatDao.delete(new LambdaQueryWrapper<Chat>().eq(Chat::getHistory_code, history_code));

        return Map.of("history_code", chatHistory.getHistory_code());
    }
}
