package com.petshop.backend.service;

import com.petshop.backend.dto.chat.ConversationResponse;
import com.petshop.backend.dto.chat.MessageResponse;
import com.petshop.backend.entity.Conversation;
import com.petshop.backend.entity.User;
import com.petshop.backend.exception.ResourceNotFoundException;
import com.petshop.backend.repository.ConversationRepository;
import com.petshop.backend.repository.MessageRepository;
import com.petshop.backend.repository.UserRepository;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ChatRealtimeService {

    private final SimpMessagingTemplate messagingTemplate;
    private final ConversationRepository conversationRepository;
    private final MessageRepository messageRepository;
    private final UserRepository userRepository;

    public ChatRealtimeService(SimpMessagingTemplate messagingTemplate, ConversationRepository conversationRepository, MessageRepository messageRepository, UserRepository userRepository) {
        this.messagingTemplate = messagingTemplate;
        this.conversationRepository = conversationRepository;
        this.messageRepository = messageRepository;
        this.userRepository = userRepository;
    }

    public void publishNewConversation(ConversationResponse conversation) {
        messagingTemplate.convertAndSend("/topic/chat/conversations", conversation);
        sendConversationToCustomerQueue(conversation);
    }

    public void publishMessage(Long conversationId, MessageResponse message) {
        messagingTemplate.convertAndSend("/topic/chat/conversations/" + conversationId, message);
    }

    public void publishConversationUpdate(Long conversationId) {
        Conversation conversation = conversationRepository.findById(conversationId)
                .orElseThrow(() -> new ResourceNotFoundException("Conversation not found"));
        List<com.petshop.backend.entity.Message> messages = messageRepository.findByConversationIdOrderByTimestampAsc(conversationId);
        com.petshop.backend.entity.Message last = messages.isEmpty() ? null : messages.get(messages.size() - 1);
        String lastMessage = last != null && last.getContent() != null ? last.getContent() : "";
        Long lastSenderId = last != null ? last.getSenderId() : null;
        ConversationResponse response = ConversationResponse.fromEntity(conversation, lastMessage, lastSenderId);

        messagingTemplate.convertAndSend("/topic/chat/conversations", response);
        sendConversationToCustomerQueue(response);
        sendConversationToStaffQueue(response);
    }

    private void sendConversationToCustomerQueue(ConversationResponse conversation) {
        User customerUser = userRepository.findById(conversation.getCustomerId())
                .orElseThrow(() -> new ResourceNotFoundException("User not found"));
        if (customerUser.getUsername() == null) {
            return;
        }
        messagingTemplate.convertAndSendToUser(customerUser.getUsername(), "/queue/chat/conversations", conversation);
    }

    private void sendConversationToStaffQueue(ConversationResponse conversation) {
        if (conversation.getStaffId() == null) {
            return;
        }
        User staffUser = userRepository.findById(conversation.getStaffId())
                .orElseThrow(() -> new ResourceNotFoundException("User not found"));
        messagingTemplate.convertAndSendToUser(staffUser.getUsername(), "/queue/chat/conversations", conversation);
    }
}
