package pl.polskalokalnie.message;

import java.util.List;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;
import pl.polskalokalnie.moderation.TextModerationService;
import pl.polskalokalnie.user.AppUser;
import pl.polskalokalnie.user.Role;
import pl.polskalokalnie.user.UserRepository;

@Service
public class MessageService {

    private final MessageRepository messageRepository;
    private final UserRepository userRepository;
    private final TextModerationService textModerationService;

    public MessageService(
            MessageRepository messageRepository,
            UserRepository userRepository,
            TextModerationService textModerationService
    ) {
        this.messageRepository = messageRepository;
        this.userRepository = userRepository;
        this.textModerationService = textModerationService;
    }

    public AppUser resolveAdmin() {
        return userRepository.findFirstByRole(Role.ADMIN)
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Brak konta administratora"));
    }

    public List<MessageResponse> getConversation(Long currentUserId, Long otherUserId) {
        messageRepository.markConversationRead(currentUserId, otherUserId);
        return messageRepository.findConversation(currentUserId, otherUserId).stream()
                .map(message -> MessageResponse.from(message, currentUserId))
                .toList();
    }

    public MessageResponse send(Long senderId, Long recipientId, String content) {
        textModerationService.validateOrThrow(content);

        Message message = new Message();
        message.setSenderId(senderId);
        message.setRecipientId(recipientId);
        message.setContent(content.trim());
        Message saved = messageRepository.save(message);
        return MessageResponse.from(saved, senderId);
    }

    public long countUnreadFrom(Long recipientId, Long senderId) {
        return messageRepository.countByRecipientIdAndSenderIdAndReadFalse(recipientId, senderId);
    }
}
