package org.example.service; import lombok.RequiredArgsConstructor; import org.example.dto.MessagePage; import org.example.dto.create.CreateMessageDto; import org.example.dto.update.UpdateMessageDto; import org.example.exception.ConflictException; import org.example.exception.ForbiddenException; import org.example.exception.NotFoundException; import org.example.model.IdempotencyKey; import org.example.model.Message; import org.example.repository.IdempotencyKeyRepository; import org.example.repository.MessageRepository; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.time.Instant; import java.util.List; import java.util.Optional; import java.util.UUID; import static org.example.config.TokenHasher.sha256; @Service @RequiredArgsConstructor public class MessageService { private final MessageRepository messageRepository; private final IdempotencyKeyRepository idempotencyKeyRepository; private final ChatService chatService; private final MessageIdempotencyWriter writer; @Transactional(readOnly = true) // или без write на этом уровне public Message sendMessage( UUID chatId, UUID senderId, CreateMessageDto messageObject, String idempotencyKey) { chatService.requireMember(chatId); if (!chatService.isMember(chatId, senderId)) { throw new ForbiddenException("Пользователь не является участником чата"); } String key = idempotencyKey.trim(); String hash = sha256(messageObject.getText()); Optional exists = idempotencyKeyRepository.findByUserIdAndChatIdAndIdempotencyKey(senderId, chatId, key); if (exists.isPresent()) { return messageFromIdem(exists.get(), hash); } try { return writer.insertNew(chatId, senderId, messageObject.getText(), key, hash); } catch (DataIntegrityViolationException e) { IdempotencyKey rec = idempotencyKeyRepository .findByUserIdAndChatIdAndIdempotencyKey(senderId, chatId, key) .orElseThrow(() -> e); return messageFromIdem(rec, hash); } } private Message messageFromIdem(IdempotencyKey row, String hash) { if (!row.getRequestHash().equals(hash)) { throw new ConflictException("Idempotency key conflict"); } return messageRepository.findById(row.getMessageId()) .orElseThrow(() -> new IllegalStateException("idempotency message missing")); } @Transactional(readOnly = true) public MessagePage getMessage(UUID chatId, UUID userId, String cursor, int limit) { if (limit < 1 || limit > 100) { throw new IllegalArgumentException("limit must be between 1 and 100"); } chatService.requireMember(chatId); if (!chatService.isMember(chatId, userId)) { throw new NotFoundException("Чат не найден"); } Pageable pageable = PageRequest.of(0, limit); List items; if (cursor == null || cursor.isBlank()) { items = messageRepository.findByChatIdOrderByCreatedAtAscIdAsc(chatId, pageable); } else { UUID cursorId; try { cursorId = UUID.fromString(cursor.trim()); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Invalid cursor"); } Message cursorMsg = messageRepository.findByIdAndChatId(cursorId, chatId) .orElseThrow(() -> new IllegalArgumentException("Invalid cursor")); items = messageRepository.findNextPage( chatId, cursorMsg.getCreatedAt(), cursorMsg.getId(), pageable ); } String nextCursor = null; if (items.size() == limit && !items.isEmpty()) { Message last = items.get(items.size() - 1); boolean hasMore = !messageRepository .findNextPage( chatId, last.getCreatedAt(), last.getId(), PageRequest.of(0, 1) ) .isEmpty(); if (hasMore) { nextCursor = last.getId().toString(); } } return new MessagePage(items, nextCursor); } @Transactional(readOnly = true) public MessagePage getMessage(String chatId, String userId, String cursor, int limit){ return getMessage(parseUuid(chatId, true), parseUuid(userId, false), cursor, limit); } @Transactional public Message updateMessage(UUID chatId, UUID messageId, UUID userId, UpdateMessageDto object) { chatService.requireMember(chatId); Message message = messageRepository.findByIdAndChatId(messageId, chatId) .orElseThrow(() -> new NotFoundException("Сообщение не найден")); if (!message.getSenderId().equals(userId)){ throw new ForbiddenException("Вы не можете редактировать чужие сообщения"); } message.setText(object.getText()); return messageRepository.save(message); } @Transactional public Message updateMessage(String chatId, String messageId, String userId, UpdateMessageDto object) { return updateMessage( parseUuid(chatId, true), parseUuid(messageId, true), parseUuid(userId, false), object); } @Transactional public void deleteMessage(UUID chatId, UUID messageId, UUID userId) { chatService.getChatById(chatId); Message msg = messageRepository.findByIdAndChatId(messageId, chatId) .orElseThrow(() -> new NotFoundException("Сообщение не найдено")); if (!msg.getSenderId().equals(userId)) { throw new ForbiddenException("Вы не можете удалять сообщения других участников"); } messageRepository.delete(msg); } @Transactional public void deleteMessage(String chatId, String messageId, String userId) { deleteMessage( parseUuid(chatId, true), parseUuid(messageId, true), parseUuid(userId, false) ); } private static UUID parseUuid(String value, boolean notFoundOnBad) { try { return UUID.fromString(value.trim()); } catch (Exception e) { if (notFoundOnBad) { throw new NotFoundException("Не найдено"); } throw new IllegalArgumentException("Invalid id"); } } }