package com.hertz.modules.ai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hertz.common.exception.BusinessException;
import com.hertz.modules.ai.entity.Conversation;
import com.hertz.modules.ai.entity.Message;
import com.hertz.modules.ai.mapper.ConversationMapper;
import com.hertz.modules.ai.mapper.MessageMapper;
import com.hertz.modules.ai.service.ConversationService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
@RequiredArgsConstructor
public class ConversationServiceImpl implements ConversationService {

    private final ConversationMapper conversationMapper;
    private final MessageMapper messageMapper;

    @Override
    @Transactional
    public Conversation createConversation(String title, Long userId) {
        Conversation conversation = new Conversation();
        conversation.setUserId(userId);
        conversation.setTitle(title != null && !title.isEmpty() ? title : "New Chat");
        conversation.setCreatedAt(LocalDateTime.now());
        conversation.setUpdatedAt(LocalDateTime.now());
        conversationMapper.insert(conversation);
        return conversation;
    }

    @Override
    public List<Conversation> getConversations(Long userId) {
        return conversationMapper.selectList(new LambdaQueryWrapper<Conversation>()
                .eq(Conversation::getUserId, userId)
                .orderByDesc(Conversation::getUpdatedAt));
    }

    @Override
    @Transactional
    public void deleteConversation(Long id, Long userId) {
        Conversation conversation = requireOwnedConversation(id, userId);
        messageMapper.delete(new LambdaQueryWrapper<Message>()
                .eq(Message::getConversationId, id));
        conversationMapper.deleteById(conversation.getId());
    }

    @Override
    public List<Conversation> searchConversations(String query, Long userId) {
        return conversationMapper.selectList(new LambdaQueryWrapper<Conversation>()
                .eq(Conversation::getUserId, userId)
                .like(Conversation::getTitle, query)
                .orderByDesc(Conversation::getUpdatedAt));
    }

    @Override
    @Transactional
    public Message saveMessage(Long conversationId, String role, String content, Long userId) {
        Conversation conversation = requireOwnedConversation(conversationId, userId);
        Message message = new Message();
        message.setConversationId(conversationId);
        message.setRole(role);
        message.setContent(content);
        message.setCreatedAt(LocalDateTime.now());
        messageMapper.insert(message);
        
        conversation.setUpdatedAt(LocalDateTime.now());
        conversationMapper.updateById(conversation);
        
        return message;
    }

    @Override
    public List<Message> getMessages(Long conversationId, Long userId) {
        requireOwnedConversation(conversationId, userId);
        return messageMapper.selectList(new LambdaQueryWrapper<Message>()
                .eq(Message::getConversationId, conversationId)
                .orderByAsc(Message::getCreatedAt));
    }

    @Override
    public List<Message> getRecentMessages(Long conversationId, Long userId, int limit) {
        requireOwnedConversation(conversationId, userId);
        if (limit <= 0) {
            return List.of();
        }
        List<Message> messages = messageMapper.selectList(new LambdaQueryWrapper<Message>()
                .eq(Message::getConversationId, conversationId)
                .orderByDesc(Message::getCreatedAt)
                .last("LIMIT " + limit));
        List<Message> copy = new ArrayList<>(messages);
        Collections.reverse(copy);
        return copy;
    }
    
    @Override
    public Conversation getConversation(Long id, Long userId) {
        return requireOwnedConversation(id, userId);
    }

    @Override
    @Transactional
    public void updateConversationTitle(Long id, String title, Long userId) {
        Conversation conversation = requireOwnedConversation(id, userId);
        conversation.setTitle(title);
        conversation.setUpdatedAt(LocalDateTime.now());
        conversationMapper.updateById(conversation);
    }

    private Conversation requireOwnedConversation(Long conversationId, Long userId) {
        if (userId == null) {
            throw new BusinessException(40100, "未登录或登录已过期");
        }
        Conversation conversation = conversationMapper.selectById(conversationId);
        if (conversation == null) {
            throw new BusinessException(40400, "会话不存在");
        }
        if (!userId.equals(conversation.getUserId())) {
            throw new BusinessException(40300, "无权限访问该会话");
        }
        return conversation;
    }
}
