package main

import (
	"context"
	"log"
	"os"
	"os/signal"
	"syscall"

	"github.com/go-redis/redis/v8"

	"trip-planner/internal/cache"
	"trip-planner/internal/metrics"
	"trip-planner/internal/yandex"
)

func main() {
	redisClient := initRedis()
	m := metrics.New()

	apiKey := os.Getenv("YANDEX_API_KEY")
	if apiKey == "" {
		log.Fatal("YANDEX_API_KEY environment variable is not set")
	}
	yandexClient := yandex.NewClient(apiKey, yandex.WithMetrics(m))

	// Define monitored stations
	monitoredStations := []string{
		// Add station IDs here
	}

	monitors := make([]*StationMonitor, 0, len(monitoredStations))
	for _, stationID := range monitoredStations {
		monitors = append(monitors, &StationMonitor{
			ID:     stationID,
			Yandex: yandexClient,
			Cache:  cache.NewCacheStore(redisClient, m),
		})
	}

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	// Set up signal handling for graceful shutdown
	sigChan := make(chan os.Signal, 1)
	signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)

	log.Println("Cron service starting, checking station statuses...")

	// Run the station status check
	if err := ProcessAllStations(ctx, monitors); err != nil {
		log.Printf("ERROR: failed to process stations: %v", err)
	}

	// Wait for signal to exit
	<-sigChan
	log.Println("Cron service shutting down...")
}

// initRedis initializes a Redis client connection.
func initRedis() *redis.Client {
	rdb := redis.NewClient(&redis.Options{
		Addr:     os.Getenv("REDIS_ADDR"),
		Password: "",
		DB:       0,
	})
	return rdb
}
