// internal/workers/audit_worker.go - FIXED
package workers

import (
	"log"
	"lost-and-found/internal/repositories"
	"time"

	"gorm.io/gorm"
)

// AuditWorker handles audit log background tasks
type AuditWorker struct {
	db           *gorm.DB
	auditLogRepo *repositories.AuditLogRepository
	stopChan     chan bool
}

// NewAuditWorker creates a new audit worker
func NewAuditWorker(db *gorm.DB) *AuditWorker {
	return &AuditWorker{
		db:           db,
		auditLogRepo: repositories.NewAuditLogRepository(db),
		stopChan:     make(chan bool),
	}
}

// Start starts the audit worker
// ✅ FIXED: Now runs in goroutine (non-blocking)
func (w *AuditWorker) Start() {
	log.Println("🔍 Audit Worker started")

	// ✅ Run in goroutine to avoid blocking
	go func() {
		ticker := time.NewTicker(24 * time.Hour) // Run daily
		defer ticker.Stop()

		for {
			select {
			case <-ticker.C:
				w.cleanupOldLogs()
			case <-w.stopChan:
				log.Println("🔍 Audit Worker stopped")
				return
			}
		}
	}()
	// ✅ Return immediately after starting goroutine
}

// Stop stops the audit worker
func (w *AuditWorker) Stop() {
	close(w.stopChan)
}

// cleanupOldLogs removes audit logs older than 1 year
func (w *AuditWorker) cleanupOldLogs() {
	log.Println("🧹 Cleaning up old audit logs...")

	cutoffDate := time.Now().AddDate(-1, 0, 0) // 1 year ago

	result := w.db.Unscoped().Where("created_at < ?", cutoffDate).Delete(&struct {
		tableName struct{} `gorm:"audit_logs"`
	}{})

	if result.Error != nil {
		log.Printf("❌ Failed to cleanup audit logs: %v", result.Error)
		return
	}

	log.Printf("✅ Cleaned up %d old audit log entries", result.RowsAffected)
}

// RunNow runs cleanup immediately (for testing)
func (w *AuditWorker) RunNow() {
	log.Println("▶️ Running audit cleanup manually...")
	w.cleanupOldLogs()
}