package pkg

import (
	"fmt"
	"time"

	_ "time/tzdata"

	socketio "github.com/googollee/go-socket.io"
	"github.com/robfig/cron/v3"
)

func JobScheduler(server *socketio.Server, cronTime string, jobFunc func()) {

	// time zone helper https://nodatime.org/TimeZones
	loc, err := time.LoadLocation(("America/Chicago"))

	if err != nil {
		fmt.Printf("There was an error getting location: %v", err)
		server.BroadcastToRoom("/", "logs", "logs", fmt.Sprintf("There was an error getting location: %v", err))
		loc = time.Local
	}

	crontJob := cron.New(cron.WithLocation(loc)) // cron.WithSeconds()

	// reference for the cron time format https://pkg.go.dev/github.com/robfig/cron@v1.2.0#hdr-CRON_Expression_Format

	// we can use 6 feilds but we need to add this in with cron.WithSeconds into our cron job other wise we can use use the standard 5 fields https://crontab.guru/
	_, err = crontJob.AddFunc(cronTime, func() {
		now := time.Now().In(loc)
		msg := fmt.Sprintf("⏰ Cron job triggered at %s (spec: %s)", now.Format(time.RFC3339), cronTime)
		fmt.Println(msg)
		server.BroadcastToRoom("/", "logs", "logs", msg)

		jobFunc()
	})
	if err != nil {
		fmt.Printf("Failed to add cron job (%s): %v\n", cronTime, err)
		server.BroadcastToRoom("/", "logs", "logs", fmt.Sprintf("Failed to add cron job (%s): %v\n", cronTime, err))
		return
	}

	crontJob.Start()
	fmt.Printf("✅ Cron job scheduled: %s (TZ: %s)\n", cronTime, loc.String())
	server.BroadcastToRoom("/", "logs", "logs", fmt.Sprintf("✅ Cron job scheduled: %s (TZ: %s)\n", cronTime, loc.String()))
}
