package db_updater

import (
	"github.com/robfig/cron/v3"
	"github.com/rs/zerolog/log"
	"thuanle.me/ip-info/configs"
	"thuanle.me/ip-info/internal/data"
)

func StartUpdateDbService() {
	c := cron.New()
	_, _ = c.AddFunc("@daily", fetchDbs)
	c.Start()
	fetchDbs()
}

func fetchDbs() {
	newFlag := false
	for _, url := range configs.GeoDbSourcePaths {
		newFlag = download(url) || newFlag
	}

	if newFlag {
		log.Info().Msg("New DB downloaded. Recreating mmdb")
		_ = mergeMmdb()

		err := data.Ins().Reload()
		if err != nil {
			log.Err(err).Msg("Failed to reload mmdb")
			return
		}
	}
}
