package handlers import ( "encoding/json" "log" "net/http" "strconv" "threadr/models" "github.com/gorilla/sessions" ) func LikeHandler(app *App) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost { http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) return } session := r.Context().Value("session").(*sessions.Session) userID, ok := session.Values["user_id"].(int) if !ok { http.Error(w, "Unauthorized", http.StatusUnauthorized) return } postIDStr := r.FormValue("post_id") postID, err := strconv.Atoi(postIDStr) if err != nil { http.Error(w, "Invalid post ID", http.StatusBadRequest) return } likeType := r.FormValue("type") if likeType != "like" && likeType != "dislike" { http.Error(w, "Invalid like type", http.StatusBadRequest) return } existingLike, err := models.GetLikeByPostAndUser(app.DB, postID, userID) if err != nil { log.Printf("Error checking existing like: %v", err) http.Error(w, "Internal Server Error", http.StatusInternalServerError) return } userAction := likeType // what the user's current vote will be after this if existingLike != nil { if existingLike.Type == likeType { // Toggle off err = models.DeleteLike(app.DB, postID, userID) userAction = "" // no active vote if err != nil { log.Printf("Error deleting like: %v", err) http.Error(w, "Internal Server Error", http.StatusInternalServerError) return } } else { err = models.UpdateLikeType(app.DB, postID, userID, likeType) if err != nil { log.Printf("Error updating like: %v", err) http.Error(w, "Internal Server Error", http.StatusInternalServerError) return } } } else { like := models.Like{ PostID: postID, UserID: userID, Type: likeType, } err = models.CreateLike(app.DB, like) if err != nil { log.Printf("Error creating like: %v", err) http.Error(w, "Internal Server Error", http.StatusInternalServerError) return } } // Fetch updated counts counts, err := models.GetLikeCountsByPostID(app.DB, postID) if err != nil { log.Printf("Error fetching like counts: %v", err) http.Error(w, "Internal Server Error", http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(map[string]interface{}{ "likes": counts.Likes, "dislikes": counts.Dislikes, "userAction": userAction, }) } }