// internal/workers/matching_worker.go - FIXED
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
// ✅ FIXED: Now runs in goroutine (non-blocking)
func (w *MatchingWorker) Start() {
	log.Println("🔗 Matching Worker started")

	// ✅ Run in goroutine to avoid blocking
	go func() {
		// 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
			}
		}
	}()
	// ✅ Return immediately after starting goroutine
}

// Stop stops the matching worker
func (w *MatchingWorker) Stop() {
	close(w.stopChan)
}

// 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()
}