package production import ( "strings" "unicode/utf8" "github.com/google/uuid" "gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto" "gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/service" ) // PrepareUser validates registration fields and assigns the new user identifier. func PrepareUser(request dto.UsersCreateRequestDTO) (dto.UserDTO, error) { if !validUsername(request.Username) || !validText(request.DisplayName, maxDisplayNameRunes) { return dto.UserDTO{}, service.ErrInvalid } return dto.UserDTO{ ID: uuid.New(), Username: request.Username, DisplayName: request.DisplayName, }, nil } // prepareChat validates the title and member identifiers before storage access. func prepareChat(request dto.ChatsCreateRequestDTO, caller uuid.UUID) (dto.ChatDTO, error) { if !validText(request.Title, maxChatTitleRunes) { return dto.ChatDTO{}, service.ErrInvalid } members, err := parseMembers(request.MemberIDs, caller) if err != nil { return dto.ChatDTO{}, err } return dto.ChatDTO{ ID: uuid.New(), Title: request.Title, MemberIDs: members, }, nil } // prepareMessage validates text and creates a record for the authorized sender and chat. func prepareMessage(request dto.MessagesCreateRequestDTO, sender, chatID uuid.UUID) (dto.MessageDTO, error) { if (strings.TrimSpace(request.Text) == "" && len(request.AttachmentIDs) == 0) || !utf8.ValidString(request.Text) || utf8.RuneCountInString(request.Text) > maxMessageRunes || len(request.AttachmentIDs) > 10 || !validIdempotencyKey(request.IdempotencyKey) { return dto.MessageDTO{}, service.ErrInvalid } seen := make(map[string]bool) for _, id := range request.AttachmentIDs { if _, err := parseID(id); err != nil || seen[id] { return dto.MessageDTO{}, service.ErrInvalid } seen[id] = true } return dto.MessageDTO{ ID: uuid.New(), ChatID: chatID, SenderID: sender, Text: request.Text, AttachmentIDs: append([]string{}, request.AttachmentIDs...), IdempotencyKey: request.IdempotencyKey, }, nil } // validIdempotencyKey accepts only the bounded ASCII alphabet from the contract. func validIdempotencyKey(key string) bool { if len(key) < 1 || len(key) > 128 { return false } for _, c := range key { if c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '.' || c == '_' || c == ':' || c == '-' { continue } return false } return true }