package matrix

import (
	"net/url"

	"maunium.net/go/mautrix/id"
)

func makeUserID(userIdentifier, homeserverURL string) (id.UserID, error) {
	userID := id.UserID(userIdentifier)
	localpart, _, err := userID.Parse()
	if err != nil {
		url, err := url.Parse(homeserverURL)
		if err != nil {
			return "", err
		}

		userID = id.NewUserID(userIdentifier, url.Host)
		if _, _, err := userID.ParseAndValidate(); err != nil {
			return "", err
		}
	} else if err := id.ValidateUserLocalpart(localpart); err != nil {
		return "", err
	} else if len(userID) > id.UserIDMaxLength {
		return "", id.ErrUserIDTooLong
	}

	return userID, nil
}
