package corpus

import (
	"time"

	"git.fjla.uk/owlboard/timetable-mgr/dbAccess"
	"git.fjla.uk/owlboard/timetable-mgr/helpers"
	"git.fjla.uk/owlboard/timetable-mgr/log"
	"go.uber.org/zap"
)

func CheckCorpus(cfg *helpers.Configuration) {
	log.Msg.Info("Checking age of CORPUS Data")
	utime, err := dbAccess.CheckUpdateTime(dbAccess.CorpusCollection)
	if err != nil {
		log.Msg.Error("Error checking last CORPUS update", zap.Error(err))
	}

	lastUpdate := time.Unix(utime, 0)
	currentTime := time.Now()
	dataAge := currentTime.Sub(lastUpdate)
	fortnight := 14 * 24 * time.Hour

	log.Msg.Debug("CORPUS Data", zap.Duration("Data Age", dataAge), zap.Duration("Max Age", 14*24*time.Hour))

	if dataAge >= fortnight {
		log.Msg.Info("CORPUS Data is more than two weeks old")
		err := RunCorpusUpdate(cfg)
		if err != nil {
			log.Msg.Warn("CORPUS Update did not run")
		}
	} else {
		log.Msg.Info("CORPUS Data is less than two weeks old")
	}
}

// Check if corpus data needs updating.
// Run update if needed.
