package ru.mtusi.messenger.controller; import jakarta.validation.Valid; import org.springframework.http.HttpStatus; import org.springframework.security.core.Authentication; import org.springframework.web.bind.annotation.*; import ru.mtusi.messenger.dto.CreateMessage; import ru.mtusi.messenger.dto.Message; import ru.mtusi.messenger.exception.InvalidRequestException; import ru.mtusi.messenger.exception.UnauthorizedException; import ru.mtusi.messenger.service.MessageService; import java.util.List; import java.util.UUID; @RestController @RequestMapping("/api/v1/chats/{chat_id}/messages") public class MessageController { private final MessageService messageService; public MessageController(MessageService messageService) { this.messageService = messageService; } @PostMapping @ResponseStatus(HttpStatus.CREATED) public Message createMessage( Authentication auth, @PathVariable("chat_id") UUID chatId, @RequestHeader(value = "Idempotency-Key", required = false) String idempotencyKey, @Valid @RequestBody CreateMessage body) { if (idempotencyKey == null || idempotencyKey.isBlank()) { throw new InvalidRequestException("Idempotency-Key header is required"); } if (!idempotencyKey.matches("^[A-Za-z0-9._:-]{1,128}$")) { throw new InvalidRequestException("Invalid Idempotency-Key format"); } return messageService.createMessage(getUserId(auth), chatId, body.text(), body.attachmentIds(), idempotencyKey); } @GetMapping public MessagePage listMessages( Authentication auth, @PathVariable("chat_id") UUID chatId, @RequestParam(value = "limit", required = false) Integer limit, @RequestParam(value = "cursor", required = false) String cursor) { int effectiveLimit = (limit == null) ? 50 : limit; if (effectiveLimit < 1 || effectiveLimit > 100) { throw new InvalidRequestException("limit must be between 1 and 100"); } java.time.OffsetDateTime lastCreatedAt = null; UUID lastId = null; if (cursor != null && !cursor.isBlank()) { try { String decoded = new String(java.util.Base64.getUrlDecoder().decode(cursor), java.nio.charset.StandardCharsets.UTF_8); String[] parts = decoded.split("\\|"); lastCreatedAt = java.time.OffsetDateTime.parse(parts[0]); lastId = UUID.fromString(parts[1]); } catch (Exception e) { throw new InvalidRequestException("Invalid cursor format"); } } // Берем на 1 больше, чтобы понять, есть ли следующая страница List msgs = messageService.getMessagesPage(getUserId(auth), chatId, lastCreatedAt, lastId, effectiveLimit + 1); boolean hasMore = msgs.size() > effectiveLimit; List pageItems = hasMore ? msgs.subList(0, effectiveLimit) : msgs; String nextCursor = null; if (hasMore && !pageItems.isEmpty()) { Message lastMsg = pageItems.get(pageItems.size() - 1); String rawCursor = lastMsg.createdAt().toString() + "|" + lastMsg.id().toString(); nextCursor = java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(rawCursor.getBytes(java.nio.charset.StandardCharsets.UTF_8)); } return new MessagePage(pageItems, nextCursor); } private UUID getUserId(Authentication auth) { if (auth == null || !(auth.getPrincipal() instanceof UUID)) { throw new UnauthorizedException("Not authenticated"); } return (UUID) auth.getPrincipal(); } public record MessagePage(List items, String nextCursor) {} }