package chat import ( "bytes" "encoding/json" "net/http" "regexp" "github.com/gin-gonic/gin" "github.com/google/uuid" "messenger/internal/platform/apperr" "messenger/internal/platform/httpx" "messenger/internal/platform/ident" "messenger/internal/platform/pagination" ) type Handler struct { chats *Service } func NewHandler(chats *Service) *Handler { return &Handler{chats: chats} } // Register mounts the chat endpoints on a router guarded by the authentication middleware. func (h *Handler) Register(protected gin.IRouter) { protected.POST("/chats", httpx.WithUser(h.create)) protected.GET("/chats", httpx.WithUser(h.list)) protected.GET("/chats/:chat_id", httpx.WithUser(h.get)) protected.POST("/chats/:chat_id/messages", httpx.WithUser(h.send)) protected.GET("/chats/:chat_id/messages", httpx.WithUser(h.history)) } type createChatRequest struct { Title string `json:"title"` MemberIDs []string `json:"member_ids"` } type createMessageRequest struct { Text *string `json:"text"` AttachmentIDs json.RawMessage `json:"attachment_ids"` } type ChatResponse struct { ID string `json:"id"` Title string `json:"title"` MemberIDs []string `json:"member_ids"` CreatedAt string `json:"created_at"` } type MessageResponse struct { AttachmentIDs []string `json:"attachment_ids"` ID string `json:"id"` ChatID string `json:"chat_id"` SenderID string `json:"sender_id"` Text string `json:"text"` CreatedAt string `json:"created_at"` } func toChatResponse(c ChatWithMembers) ChatResponse { members := make([]string, 0, len(c.MemberIDs)) for _, m := range c.MemberIDs { members = append(members, m.String()) } return ChatResponse{ ID: c.ID.String(), Title: c.Title, MemberIDs: members, CreatedAt: httpx.Timestamp(c.CreatedAt), } } func toMessageResponse(m Message) MessageResponse { ids := make([]string, 0, len(m.AttachmentIDs)) for _, id := range m.AttachmentIDs { ids = append(ids, id.String()) } return MessageResponse{ AttachmentIDs: ids, ID: m.ID.String(), ChatID: m.ChatID.String(), SenderID: m.SenderID.String(), Text: m.Text, CreatedAt: httpx.Timestamp(m.CreatedAt), } } func (h *Handler) create(c *gin.Context, actor uuid.UUID) { var req createChatRequest if err := httpx.DecodeJSON(c, &req); err != nil { httpx.Error(c, err) return } members := make([]uuid.UUID, 0, len(req.MemberIDs)) for _, raw := range req.MemberIDs { id, err := ident.Parse(raw) if err != nil { httpx.Error(c, apperr.Invalid("member_ids must contain valid UUIDs")) return } members = append(members, id) } chat, err := h.chats.Create(c.Request.Context(), actor, req.Title, members) if err != nil { httpx.Error(c, err) return } httpx.JSON(c, http.StatusCreated, toChatResponse(chat)) } func (h *Handler) list(c *gin.Context, actor uuid.UUID) { limit, after, err := listing(c, actor) if err != nil { httpx.Error(c, err) return } page, err := h.chats.List(c.Request.Context(), actor, after, limit) if err != nil { httpx.Error(c, err) return } httpx.JSON(c, http.StatusOK, pagination.ToResponse(page, actor, toChatResponse)) } func (h *Handler) get(c *gin.Context, actor uuid.UUID) { chatID, err := chatParam(c) if err != nil { httpx.Error(c, err) return } chat, err := h.chats.Get(c.Request.Context(), actor, chatID) if err != nil { httpx.Error(c, err) return } httpx.JSON(c, http.StatusOK, toChatResponse(chat)) } func (h *Handler) send(c *gin.Context, actor uuid.UUID) { chatID, err := chatParam(c) if err != nil { httpx.Error(c, err) return } key, err := idempotencyKey(c) if err != nil { httpx.Error(c, err) return } var req createMessageRequest if err := httpx.DecodeJSON(c, &req); err != nil { httpx.Error(c, err) return } if req.Text == nil { httpx.Error(c, apperr.Invalid("text must be a string")) return } attachments, err := decodeAttachmentIDs(req.AttachmentIDs) if err != nil { httpx.Error(c, err) return } message, err := h.chats.Send(c.Request.Context(), actor, MessagePayload{ChatID: chatID, IdempotencyKey: key, Text: *req.Text, AttachmentIDs: attachments}) if err != nil { httpx.Error(c, err) return } httpx.JSON(c, http.StatusCreated, toMessageResponse(message)) } func (h *Handler) history(c *gin.Context, actor uuid.UUID) { chatID, err := chatParam(c) if err != nil { httpx.Error(c, err) return } limit, after, err := listing(c, chatID) if err != nil { httpx.Error(c, err) return } page, err := h.chats.History(c.Request.Context(), actor, chatID, after, limit) if err != nil { httpx.Error(c, err) return } httpx.JSON(c, http.StatusOK, pagination.ToResponse(page, chatID, toMessageResponse)) } var keyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`) // idempotencyKey rejects two values of the header as ambiguous. func idempotencyKey(c *gin.Context) (string, error) { values := c.Request.Header.Values("Idempotency-Key") if len(values) != 1 || !keyPattern.MatchString(values[0]) { return "", apperr.Invalid("Idempotency-Key header is required: one value of 1-128 characters A-Z a-z 0-9 . _ : -") } return values[0], nil } func chatParam(c *gin.Context) (uuid.UUID, error) { id, err := ident.Parse(c.Param("chat_id")) if err != nil { return uuid.Nil, apperr.Invalid("chat_id must be a UUID") } return id, nil } // listing parses limit and cursor; the cursor must belong to scope, and a // present but empty cursor is rejected like a malformed one. func listing(c *gin.Context, scope uuid.UUID) (int, *uuid.UUID, error) { limit, err := pagination.ParseLimit(c.Query("limit")) if err != nil { return 0, nil, apperr.Wrap(apperr.KindInvalid, err.Error(), err) } token, present := c.GetQuery("cursor") if !present { return limit, nil, nil } last, err := pagination.DecodeCursor(token, scope) if err != nil { return 0, nil, apperr.Wrap(apperr.KindInvalid, "cursor is invalid for this resource", err) } return limit, &last, nil } // RawMessage distinguishes an omitted optional array from an explicit null. func decodeAttachmentIDs(raw json.RawMessage) ([]uuid.UUID, error) { if raw == nil { return nil, nil } if bytes.Equal(bytes.TrimSpace(raw), []byte("null")) { return nil, apperr.Invalid("attachment_ids must be an array") } var values []string if err := json.Unmarshal(raw, &values); err != nil { return nil, apperr.Invalid("attachment_ids must be an array of UUIDs") } if len(values) > MaxAttachments { return nil, apperr.Invalid("attachment_ids must have at most 10 entries") } ids := make([]uuid.UUID, 0, len(values)) for _, value := range values { id, err := ident.Parse(value) if err != nil { return nil, apperr.Invalid("attachment_ids must contain valid UUIDs") } ids = append(ids, id) } return ids, nil }