package com.smyhub.store.mengyastorebackendjava.service;

import com.smyhub.store.mengyastorebackendjava.dto.response.ChatMessageResponse;
import com.smyhub.store.mengyastorebackendjava.entity.ChatMessage;
import com.smyhub.store.mengyastorebackendjava.exception.BusinessException;
import com.smyhub.store.mengyastorebackendjava.repository.ChatMessageRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Service
@RequiredArgsConstructor
public class ChatService {

    private final ChatMessageRepository chatMessageRepository;
    private final Map<String, LocalDateTime> lastSentMap = new ConcurrentHashMap<>();

    public List<ChatMessageResponse> getUserMessages(String accountId) {
        return chatMessageRepository.findByAccountIdOrderBySentAtAsc(accountId)
                .stream().map(this::toResponse).toList();
    }

    @Transactional
    public ChatMessageResponse sendUserMessage(String accountId, String accountName, String content) {
        LocalDateTime last = lastSentMap.get(accountId);
        if (last != null && last.plusSeconds(1).isAfter(LocalDateTime.now())) {
            throw new BusinessException("发送太频繁，请稍后再试", HttpStatus.TOO_MANY_REQUESTS);
        }
        lastSentMap.put(accountId, LocalDateTime.now());

        ChatMessage msg = new ChatMessage();
        msg.setId(UUID.randomUUID().toString());
        msg.setAccountId(accountId);
        msg.setAccountName(accountName);
        msg.setContent(content);
        msg.setSentAt(LocalDateTime.now());
        msg.setFromAdmin(false);
        return toResponse(chatMessageRepository.save(msg));
    }

    public Map<String, List<ChatMessageResponse>> listAllConversations() {
        Map<String, List<ChatMessageResponse>> result = new LinkedHashMap<>();
        chatMessageRepository.findAllByOrderByAccountIdAscSentAtAsc().forEach(row -> {
            result.computeIfAbsent(row.getAccountId(), k -> new ArrayList<>()).add(toResponse(row));
        });
        return result;
    }

    public List<ChatMessageResponse> getConversation(String accountId) {
        return chatMessageRepository.findByAccountIdOrderBySentAtAsc(accountId)
                .stream().map(this::toResponse).toList();
    }

    @Transactional
    public ChatMessageResponse sendAdminMessage(String accountId, String content) {
        ChatMessage msg = new ChatMessage();
        msg.setId(UUID.randomUUID().toString());
        msg.setAccountId(accountId);
        msg.setAccountName("管理员");
        msg.setContent(content);
        msg.setSentAt(LocalDateTime.now());
        msg.setFromAdmin(true);
        return toResponse(chatMessageRepository.save(msg));
    }

    @Transactional
    public void clearConversation(String accountId) {
        chatMessageRepository.deleteByAccountId(accountId);
    }

    private ChatMessageResponse toResponse(ChatMessage m) {
        return ChatMessageResponse.builder()
                .id(m.getId())
                .accountId(m.getAccountId())
                .accountName(m.getAccountName())
                .content(m.getContent())
                .sentAt(m.getSentAt())
                .fromAdmin(m.isFromAdmin())
                .build();
    }
}
