package workers import ( "fmt" "gorm.io/gorm" db "git.zervo.org/scheduletogether/backend/internal/database" ) func workerFriends_PurgeAbandonedRequests() { reporter := NewReporter("Friends", "PurgeAbandonedRequests") // Start a transaction tx := db.Db.Begin() // Get all friend requests reporter.Status("1/2: Get all friend requests") var friendRequests []db.FriendRequest err := tx.Model(&db.FriendRequest{}).Find(&friendRequests).Error if err != nil { tx.Rollback() reporter.Fail("Failed to retrieve friend requests from the database: " + err.Error()) return } reporter.Status(fmt.Sprintf("Found %d pending requests", len(friendRequests))) // Loop over friend requests reporter.Status("2/2: Purge abandoned friend requests") var purged int for _, request := range friendRequests { // Get source user var sourceUser db.User err = tx.Where("uuid = ?", request.Source).First(&sourceUser).Error // If error, assume user doesn't exist anymore if err != nil { reporter.Status("Deleting abandoned friend request with source user " + request.Source) purged += 1 err := tx.Model(&db.FriendRequest{}).Delete(&request).Error if err != nil { tx.Rollback() reporter.Fail("Failed to delete friend request from the database: " + err.Error()) return } continue } reporter.Status(fmt.Sprintf("Purged %d abandoned requests", purged)) // Get target user var targetUser db.User err = tx.Where("uuid = ?", request.Source).First(&targetUser).Error // If error, assume user doesn't exist anymore if err != nil { if err == gorm.ErrRecordNotFound { reporter.Status("Deleting abandoned friend request with target user " + request.Target) err := tx.Model(&db.FriendRequest{}).Delete(&request).Error if err != nil { tx.Rollback() reporter.Fail("Failed to delete friend request from the database: " + err.Error()) return } continue } } } // Commit the transaction if everything is successful err = tx.Commit().Error if err != nil { tx.Rollback() reporter.Fail("Failed to commit transaction: " + err.Error()) return } // Finish job reporter.Finish() }