package maintenance

import (
	"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(1 * time.Minute)
	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", len(services))
	for _, service := range services {
		// Update the service score
		service.Score = utils.ComputeScore(&service)
		log.Debug().Msgf("Maintenance: Updating score for %v with %v", service.Name, service.Score)
		// Save the service
		err := database.Pb.UpdateService(service.ID, service)
		if err != nil {
			log.Error().Err(err).Msg("Error updating service")
			continue
		}
	}
}
