package handler import ( "context" "encoding/json" "log/slog" "net/http" "gitea.michaelthomson.dev/mthomson/habits/internal/user/service" "github.com/gofrs/uuid/v5" ) type UserRegisterer interface { Register(ctx context.Context, email string, password string) (uuid.UUID, error) } type RegisterRequest struct { Email string `json:"email"` Password string `json:"password"` } type RegisterResponse struct { Id string `json:"id"` } func HandleRegisterUser(logger *slog.Logger, userService UserRegisterer) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { ctx := r.Context() registerRequest := RegisterRequest{} decoder := json.NewDecoder(r.Body) decoder.DisallowUnknownFields() err := decoder.Decode(®isterRequest) if err != nil { logger.ErrorContext(ctx, err.Error()) http.Error(w, "", http.StatusBadRequest) return } uuid, err := userService.Register(ctx, registerRequest.Email, registerRequest.Password) if err != nil { if err == service.ErrUserExists { http.Error(w, "", http.StatusConflict) return } logger.ErrorContext(ctx, err.Error()) http.Error(w, "", http.StatusInternalServerError) return } response := RegisterResponse{uuid.String()} w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) err = json.NewEncoder(w).Encode(response) if err != nil { logger.ErrorContext(ctx, err.Error()) http.Error(w, "", http.StatusInternalServerError) return } } }