package ru.mtusi.messenger.service; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import ru.mtusi.messenger.dto.Message; import ru.mtusi.messenger.entity.AttachmentEntity; import ru.mtusi.messenger.entity.ChatEntity; import ru.mtusi.messenger.entity.MessageEntity; import ru.mtusi.messenger.exception.ConflictException; import ru.mtusi.messenger.exception.InvalidRequestException; import ru.mtusi.messenger.exception.NotFoundException; import ru.mtusi.messenger.repository.AttachmentRepository; import ru.mtusi.messenger.repository.ChatRepository; import ru.mtusi.messenger.repository.IdempotencyRepository; import ru.mtusi.messenger.repository.MessageRepository; import java.time.OffsetDateTime; import java.time.ZoneOffset; import java.util.List; import java.util.UUID; @Service public class MessageService { private final MessageRepository messageRepository; private final ChatRepository chatRepository; private final IdempotencyRepository idempotencyRepository; private final AttachmentRepository attachmentRepository; public MessageService(MessageRepository messageRepository, ChatRepository chatRepository, IdempotencyRepository idempotencyRepository, AttachmentRepository attachmentRepository) { this.messageRepository = messageRepository; this.chatRepository = chatRepository; this.idempotencyRepository = idempotencyRepository; this.attachmentRepository = attachmentRepository; } @Transactional public Message createMessage(UUID callerId, UUID chatId, String text, List attachmentIds, String idempotencyKey) { verifyAccess(callerId, chatId); if (text == null) text = ""; if (text.isBlank() && (attachmentIds == null || attachmentIds.isEmpty())) { throw new InvalidRequestException("Message must have text or attachments"); } // Проверяем вложения if (attachmentIds != null && !attachmentIds.isEmpty()) { for (UUID attId : attachmentIds) { AttachmentEntity att = attachmentRepository.findById(attId) .orElseThrow(() -> new NotFoundException("Attachment not found: " + attId)); if (!att.getChatId().equals(chatId)) { throw new NotFoundException("Attachment not found in this chat"); } } } // Считаем хеш тела запроса String requestHash = org.springframework.util.DigestUtils.md5DigestAsHex( (text + attachmentIds).getBytes(java.nio.charset.StandardCharsets.UTF_8)); if (idempotencyKey != null && !idempotencyKey.isBlank()) { var existing = idempotencyRepository.findById(new ru.mtusi.messenger.entity.IdempotencyId(idempotencyKey, callerId, chatId)); if (existing.isPresent()) { if (!existing.get().getRequestHash().equals(requestHash)) { throw new ConflictException("Idempotency key reused with different body"); } return messageRepository.findById(existing.get().getMessageId()) .map(this::toDto) .orElseThrow(() -> new NotFoundException("Message not found")); } } MessageEntity msg = new MessageEntity(); msg.setId(UUID.randomUUID()); msg.setChatId(chatId); msg.setSenderId(callerId); msg.setText(text); msg.setCreatedAt(OffsetDateTime.now(ZoneOffset.UTC).truncatedTo(java.time.temporal.ChronoUnit.MILLIS)); messageRepository.save(msg); // Связываем вложения if (attachmentIds != null && !attachmentIds.isEmpty()) { for (UUID attId : attachmentIds) { messageRepository.linkAttachment(msg.getId(), attId); } } // Сохраняем ключ идемпотентности if (idempotencyKey != null && !idempotencyKey.isBlank()) { var idem = new ru.mtusi.messenger.entity.IdempotencyEntity(); idem.setKey(idempotencyKey); idem.setUserId(callerId); idem.setChatId(chatId); idem.setRequestHash(requestHash); idem.setMessageId(msg.getId()); idem.setCreatedAt(OffsetDateTime.now(ZoneOffset.UTC)); idempotencyRepository.save(idem); } return toDto(msg); } private void verifyAccess(UUID callerId, UUID chatId) { ChatEntity chat = chatRepository.findById(chatId) .orElseThrow(() -> new NotFoundException("Chat not found")); boolean isMember = chat.getMembers().stream().anyMatch(u -> u.getId().equals(callerId)); if (!isMember) throw new NotFoundException("Chat not found"); } private Message toDto(MessageEntity e) { List attachments = messageRepository.findAttachmentIdsByMessageId(e.getId()); return new Message( e.getId(), e.getChatId(), e.getSenderId(), e.getText(), attachments, e.getCreatedAt() ); } @Transactional(readOnly = true) public List getMessagesPage(UUID callerId, UUID chatId, OffsetDateTime lastCreatedAt, UUID lastId, int limit) { verifyAccess(callerId, chatId); OffsetDateTime startTime = (lastCreatedAt != null) ? lastCreatedAt : OffsetDateTime.of(1970, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); UUID startId = (lastId != null) ? lastId : new UUID(0, 0); return messageRepository.findNextPage(chatId, startTime, startId, org.springframework.data.domain.PageRequest.of(0, limit)) .stream().map(this::toDto).toList(); } }