diff --git a/internal/services/postService.go b/internal/services/postService.go index aff99db..a34c355 100644 --- a/internal/services/postService.go +++ b/internal/services/postService.go @@ -7,6 +7,7 @@ import ( "context" "encoding/json" "fmt" + "math/rand" "net/http" "strings" @@ -106,19 +107,33 @@ func (ps *PostService) InsertNewAccounts(newAccounts []domain.Account) int { func (ps *PostService) GetRandomPost() domain.Post { var post domain.Post - orderExpr := "RANDOM()" // sqlite - if config.Config.DBEngine != "sqlite" { - orderExpr = "RAND()" // mariadb/mysql + var postIDs []uint + + // AI Enhanced + // Step 1: Fetch eligible post IDs (with at least one approved attachment) + ps.db. + Model(&domain.Post{}). + Where("exists (select 1 from media_attachments where post_id = posts.id and approved = ?)", true). + Pluck("id", &postIDs) + + if len(postIDs) == 0 { + return domain.Post{} // No eligible posts } + + // Step 2: Pick a random ID in Go + randomID := postIDs[rand.Intn(len(postIDs))] + + // Step 3: Load the full post with related data ps.db. Preload("Account"). Preload("Attachments", "Approved = ?", true). - Where("exists (select 1 from media_attachments where post_id = posts.id and approved = ?)", true). - Order(orderExpr). - First(&post) + First(&post, randomID) + + // Step 4: Keep only the first attachment if any if len(post.Attachments) > 0 { post.Attachments = []domain.MediaAttachment{post.Attachments[0]} } + return post }