package currency

import (
	"context"
	"fmt"
	"log/slog"
	"time"

	"github.com/SamuelTariku/FortuneBet-Backend/internal/config"
	"github.com/go-co-op/gocron"
)

type ExchangeRateWorker struct {
	fetcherService *FixerFetcher
	scheduler      *gocron.Scheduler
	logger         *slog.Logger
	cfg            *config.Config
}

func NewExchangeRateWorker(
	fetcherService *FixerFetcher, logger *slog.Logger, cfg *config.Config,
) *ExchangeRateWorker {
	return &ExchangeRateWorker{
		fetcherService: fetcherService,
		scheduler:      gocron.NewScheduler(time.UTC),
		logger:         logger,
		cfg:            cfg,
	}
}

func (w *ExchangeRateWorker) Start(ctx context.Context) {
	_, err := w.scheduler.Every(6).Hours().Do(w.RunUpdate)
	if err != nil {
		return
	}

	// Run immediately on startup
	go w.RunUpdate()

	w.scheduler.StartAsync()
}

func (w *ExchangeRateWorker) RunUpdate() {
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	if _, err := w.fetcherService.FetchLatestRates(ctx, w.cfg.BASE_CURRENCY); err != nil {
		fmt.Println("Exchange rate update failed", "error", err)
	}
}

func (w *ExchangeRateWorker) Stop() {
	w.scheduler.Stop()
	w.logger.Info("Exchange rate worker stopped")
}
