package messages import ( "gitflic.ru/project/bulla-max/mtusi2026lab1/internal/common" "gitflic.ru/project/bulla-max/mtusi2026lab1/internal/storage" "github.com/gofiber/fiber/v3" "github.com/google/uuid" ) func createMessage(c fiber.Ctx) error { userID := c.Locals("userID").(uuid.UUID) chatID, err := uuid.Parse(c.Params("chat_id")) if err != nil { return common.SendAppError(c, ErrInvalidChatID) } var req CreateMessageRequest if err := common.BindJSON(c, &req); err != nil { return common.SendAppError(c, err) } if msg := common.ValidateMessageText(req.Text); msg != "" { return common.SendError(c, fiber.StatusBadRequest, common.ErrorCodeInvalidRequest, msg) } var message Message err = storage.GlobalStore.Update(func(tx storage.Tx) error { if !tx.IsMember(userID, chatID) { return ErrChatNotFound } message = NewMessage(chatID, userID, req.Text) tx.CreateMessage(message) return nil }) if err != nil { return common.SendAppError(c, err) } return c.Status(fiber.StatusCreated).JSON(message) } func listMessages(c fiber.Ctx) error { userID := c.Locals("userID").(uuid.UUID) chatID, err := uuid.Parse(c.Params("chat_id")) if err != nil { return common.SendAppError(c, ErrInvalidChatID) } limit, err := common.ParseLimit(c, 50) if err != nil { return common.SendAppError(c, err) } cursor, err := common.ParseCursor(c) if err != nil { return common.SendAppError(c, err) } if cursor != nil && chatID != cursor.ContextID { return common.SendError(c, fiber.StatusBadRequest, common.ErrorCodeInvalidRequest, "bad cursor value") } var page *common.PaginatedResponse[storage.Entity] err = storage.GlobalStore.View(func(tx storage.ReadOnlyTx) error { if !tx.IsMember(userID, chatID) { return ErrChatNotFound } found, fetchErr := tx.GetChatMessages(chatID, limit, cursor) page = found return fetchErr }) if err != nil { return common.SendAppError(c, err) } return c.JSON(page) }