package maintenance

import (
	"sync"
	"time"

	"github.com/rs/zerolog/log"

	"pluja.dev/kycnot.me/database"
	"pluja.dev/kycnot.me/utils"
)

func InitMaintenanceDaemon() {
	go daemon()
}

func daemon() {
	// Run the first update
	updateScores()
	ticker := time.NewTicker(24 * time.Hour)
	go func() {
		for {
			<-ticker.C
			updateScores()
		}
	}()
	select {}
}

func updateScores() {
	//log.Info().Msg("Maintenance: Updating scores")
	//oneHourAgoString := time.Now().Add(-1 * time.Hour).Format(time.RFC3339)
	//filter := fmt.Sprintf("score=0 || updated >= '%v'", oneHourAgoString)
	filter := ""
	services, err := database.Pb.GetServices(filter, "")
	if err != nil {
		log.Error().Err(err).Msg("Error getting services")
		return
	}

	log.Debug().Msgf("Maintenance: Updating %v services scores..", len(services))
	var wg sync.WaitGroup
	for _, service := range services {
		wg.Add(1)
		go func(s database.Service) {
			defer wg.Done()
			// Update the service score
			s.Score, _ = utils.ComputeScore(&s)
			//log.Debug().Msgf("Maintenance: Updating score for %v with %v", service.Name, service.Score)
			// Save the service
			err := database.Pb.UpdateService(s.ID, s)
			if err != nil {
				log.Error().Err(err).Msg("Error updating service")
				return
			}
		}(service)
	}
	wg.Wait()
	log.Debug().Msgf("Maintenance: Updated %d services", len(services))
}
