package http import ( "encoding/json" "errors" "net/http" "github.com/charawein/mtusi2026lab6/internal/service" "github.com/charawein/mtusi2026lab6/internal/transport/httputil" ) type MessageHandler struct { messages *service.MessageService } func NewMessageHandler(messages *service.MessageService) *MessageHandler { return &MessageHandler{messages: messages} } // attachmentIDs — поле контракта, которое обязано быть JSON-массивом строк. // null недопустим (в отличие от отсутствия поля — его трактуем как пустой // список и пробрасываем дальше как nil-срез). type attachmentIDs struct { present bool value []string } var errAttachmentIDsNull = errors.New("attachment_ids must be an array, not null") func (a *attachmentIDs) UnmarshalJSON(b []byte) error { a.present = true if string(b) == "null" { return errAttachmentIDsNull } var v []string if err := json.Unmarshal(b, &v); err != nil { return err } a.value = v return nil } func (h *MessageHandler) SendMessage(w http.ResponseWriter, r *http.Request) { uid := httputil.UserIDFromContext(r.Context()) if uid == "" { httputil.WriteError(w, r, service.ErrUnauthorized) return } chatID := r.PathValue("chat_id") if chatID == "" { httputil.WriteError(w, r, service.ErrInvalidInput) return } var body struct { Text *string `json:"text"` AttachmentIDs attachmentIDs `json:"attachment_ids"` } if err := httputil.DecodeJSON(r, &body); err != nil { httputil.WriteError(w, r, err) return } if body.Text == nil { // text обязателен по контракту, даже пустой httputil.WriteError(w, r, service.ErrInvalidInput) return } // null в attachment_ids — нарушение контракта; отсутствие поля считаем // пустым списком. if body.AttachmentIDs.present && body.AttachmentIDs.value == nil { // present == true и value == nil возможно только если был null — // но UnmarshalJSON уже вернул ошибку. Оставляем защиту на будущее. httputil.WriteError(w, r, service.ErrInvalidInput) return } // Повтор с тем же ключом возвращает тот же 201 и то же сообщение. key := r.Header.Get("Idempotency-Key") m, err := h.messages.Send(r.Context(), uid, chatID, *body.Text, body.AttachmentIDs.value, key) if err != nil { httputil.WriteError(w, r, err) return } httputil.WriteJSON(w, r, http.StatusCreated, m) } func (h *MessageHandler) ListMessages(w http.ResponseWriter, r *http.Request) { uid := httputil.UserIDFromContext(r.Context()) if uid == "" { httputil.WriteError(w, r, service.ErrUnauthorized) return } chatID := r.PathValue("chat_id") if chatID == "" { httputil.WriteError(w, r, service.ErrInvalidInput) return } limit, err := httputil.ParseLimit(r) if err != nil { httputil.WriteError(w, r, err) return } cursor := r.URL.Query().Get("cursor") items, next, err := h.messages.List(r.Context(), uid, chatID, cursor, limit) if err != nil { httputil.WriteError(w, r, err) return } httputil.WriteJSON(w, r, http.StatusOK, httputil.PageResponse{Items: items, NextCursor: httputil.NextOrNull(next)}) }