2025-11-23 22:49:46 +07:00

90 lines
2.1 KiB
Go

// internal/workers/matching_worker.go
package workers
import (
"log"
"lost-and-found/internal/repositories"
"lost-and-found/internal/services"
"time"
"gorm.io/gorm"
)
// MatchingWorker handles automatic matching of lost and found items
type MatchingWorker struct {
db *gorm.DB
matchService *services.MatchService
itemRepo *repositories.ItemRepository
lostItemRepo *repositories.LostItemRepository
stopChan chan bool
}
// NewMatchingWorker creates a new matching worker
func NewMatchingWorker(db *gorm.DB) *MatchingWorker {
return &MatchingWorker{
db: db,
matchService: services.NewMatchService(db),
itemRepo: repositories.NewItemRepository(db),
lostItemRepo: repositories.NewLostItemRepository(db),
stopChan: make(chan bool),
}
}
// Start starts the matching worker
func (w *MatchingWorker) Start() {
log.Println("🔗 Matching Worker started")
// Run every 30 minutes
ticker := time.NewTicker(30 * time.Minute)
defer ticker.Stop()
for {
select {
case <-ticker.C:
w.performMatching()
case <-w.stopChan:
log.Println("🔗 Matching Worker stopped")
return
}
}
}
// Stop stops the matching worker
func (w *MatchingWorker) Stop() {
w.stopChan <- true
}
// performMatching performs automatic matching between lost and found items
func (w *MatchingWorker) performMatching() {
log.Println("🔍 Performing automatic matching...")
// Get all unclaimed items
items, _, err := w.itemRepo.FindAll(1, 1000, "unclaimed", "", "")
if err != nil {
log.Printf("❌ Error fetching items: %v", err)
return
}
if len(items) == 0 {
log.Println("✅ No unclaimed items to match")
return
}
matchCount := 0
for _, item := range items {
// Auto-match with lost items
if err := w.matchService.AutoMatchNewItem(item.ID); err != nil {
log.Printf("❌ Failed to match item ID %d: %v", item.ID, err)
continue
}
matchCount++
}
log.Printf("✅ Completed matching for %d items", matchCount)
}
// RunNow runs matching immediately (for testing)
func (w *MatchingWorker) RunNow() {
log.Println("▶️ Running matching manually...")
w.performMatching()
}