package handler import ( "highload/internal/service" "highload/internal/transport/http/httputils" "highload/internal/transport/http/middleware" "net/http" ) type MessageHandler struct { messageService *service.MessageService } func NewMessageHandler(messageService *service.MessageService) *MessageHandler { return &MessageHandler{messageService: messageService} } func (h *MessageHandler) CreateMessage(w http.ResponseWriter, r *http.Request) { requestID := middleware.RequestIDFromContext(r.Context()) userID := middleware.UserIDFromContext(r.Context()) chatID := r.PathValue("chat_id") req, code := httputils.Decode[messageCreateRequest](r) if code != http.StatusOK { if code == http.StatusUnsupportedMediaType { httputils.WriteError(w, code, httputils.ErrorDetails{Code: "unsupported_media_type", Message: "Неверный media type", RequestID: requestID}) return } httputils.WriteError(w, code, httputils.ErrorDetails{Code: "invalid_request", Message: "Неверный запрос", RequestID: requestID}) return } key := r.Header.Get("Idempotency-Key") if ok := httputils.CheckIdempotencyKeyPattern(key); !ok { httputils.WriteError(w, http.StatusBadRequest, httputils.ErrorDetails{ Code: "invalid_request", Message: "wrong Idempotency-Key", RequestID: requestID, }) return } message, err := h.messageService.CreateMessage(r.Context(), req.Text, chatID, userID, key) if err != nil { httputils.WriteServiceError(w, err, requestID) return } response := convertMessageModelToResponse(message) _ = httputils.WriteJSON[messageResponse](w, http.StatusCreated, *response) } func (h *MessageHandler) GetMessagesByChatID(w http.ResponseWriter, r *http.Request) { requestID := middleware.RequestIDFromContext(r.Context()) userID := middleware.UserIDFromContext(r.Context()) chatID := r.PathValue("chat_id") limit, cursor, ok := httputils.GetLimitAndCursor(r) if !ok { httputils.WriteError(w, http.StatusBadRequest, httputils.ErrorDetails{Code: "invalid_request", Message: "Неверный запрос", RequestID: requestID}) return } messages, nextCursor, err := h.messageService.GetMessagesByChatID(r.Context(), chatID, userID, limit, cursor) if err != nil { httputils.WriteServiceError(w, err, requestID) return } messageResponses := make([]messageResponse, len(messages)) for index, message := range messages { messageResponses[index] = *convertMessageModelToResponse(message) } response := messageGetResponse{ Items: messageResponses, NextCursor: nextCursor, } _ = httputils.WriteJSON[messageGetResponse](w, http.StatusOK, response) }