package ru.mtusi.messenger.service; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import ru.mtusi.messenger.dto.ChatDTO; import ru.mtusi.messenger.dto.ChatPageDTO; import ru.mtusi.messenger.exception.InvalidRequestException; import ru.mtusi.messenger.exception.NotFoundException; import ru.mtusi.messenger.mapper.ChatMapper; import ru.mtusi.messenger.model.Chat; import ru.mtusi.messenger.model.User; import ru.mtusi.messenger.repository.ChatRepository; import ru.mtusi.messenger.validation.ChatValidator; import ru.mtusi.messenger.util.CursorCodec; import java.util.*; @Service @Slf4j @RequiredArgsConstructor public class ChatService { private final ChatMapper chatMapper; private final ChatValidator chatValidator; private final ChatRepository chatRepository; @Transactional public ChatDTO createChat(UUID caller, ChatDTO chatDTO) { Set members = chatValidator.validateCreate(caller, chatDTO); Chat chat = buildChat(chatDTO, members); chat = persistChat(chat); return chatMapper.toChatDto(chat); } private Chat buildChat(ChatDTO chatDTO, Set members) { Chat chat = chatMapper.toChat(chatDTO); chat.setMembers(members); return chat; } private Chat persistChat(Chat chat) { try { return chatRepository.saveAndFlush(chat); } catch (DataIntegrityViolationException e) { throw new InvalidRequestException("Cannot create chat: invalid data"); } } @Transactional(readOnly = true) public ChatDTO getChatDTO(UUID caller, UUID chatId) { Chat chat = requireChatForMember(caller, chatId); return chatMapper.toChatDto(chat); } @Transactional(readOnly = true) public Chat getChat(UUID caller, UUID chatId) { return requireChatForMember(caller, chatId); } private Chat requireChatForMember(UUID caller, UUID chatId) { Chat chat = chatRepository.findById(chatId) .orElseThrow(() -> new NotFoundException("Chat not found")); if (chat.getMembers().stream().noneMatch(m -> m.getId().equals(caller))) { throw new NotFoundException("Chat not found"); } return chat; } @Transactional(readOnly = true) public ChatPageDTO listChats(UUID userId, Integer limit, String cursor) { int size = resolveSize(limit); CursorCodec.Cursor decoded = parseChatsCursor(cursor); List rows = loadChatPage(userId, decoded, size); return buildPage(rows, size); } private int resolveSize(Integer limit) { return (limit == null) ? 50 : limit; } private List loadChatPage(UUID userId, CursorCodec.Cursor cursor, int size) { if (cursor == null) { return chatRepository.findPageByMember(userId, Pageable.ofSize(size + 1)); } return chatRepository.findPageByMemberAfterCursor( userId, cursor.boundary().createdAt(), cursor.boundary().id(), Pageable.ofSize(size + 1)); } private CursorCodec.Cursor parseChatsCursor(String cursor) { if (cursor == null || cursor.isBlank()) { return null; } CursorCodec.Cursor decoded = CursorCodec.decode(cursor); if (decoded.scopeId() != null) { throw new InvalidRequestException("Invalid cursor"); } return decoded; } private ChatPageDTO buildPage(List rows, int size) { List items = rows.stream() .limit(size) .map(chatMapper::toChatDto) .toList(); ChatPageDTO page = new ChatPageDTO(); page.setItems(items); page.setNextCursor(buildNextCursor(rows, size)); return page; } private String buildNextCursor(List rows, int size) { if (rows.size() <= size) { return null; } Chat last = rows.get(size - 1); return CursorCodec.encode(null, boundaryOf(last)); } private CursorCodec.PageBoundary boundaryOf(Chat chat) { return new CursorCodec.PageBoundary(chat.getCreatedAt(), chat.getId()); } }