package main

import (
	"net/http"
	"time"

	"github.com/fiskerinc/cloud-services/services/cost/handlers"
	"github.com/fiskerinc/cloud-services/services/cost/services"

	"github.com/fiskerinc/cloud-services/pkg/health"
	"github.com/fiskerinc/cloud-services/pkg/logger"
	"github.com/fiskerinc/cloud-services/pkg/utils/app"
	"github.com/fiskerinc/cloud-services/pkg/utils/envtool"
)

func main() {
	app.Setup("cost", func() {})

	// Initialize services
	services.InitClickhouse()

	// Start metrics collector in background
	collectorInterval := envtool.GetEnvInt("COLLECTOR_INTERVAL_MINUTES", 15)
	go services.StartMetricsCollector(time.Duration(collectorInterval) * time.Minute)

	// Setup HTTP routes
	mux := http.NewServeMux()
	mux.HandleFunc("/cost/vin/", handlers.GetVinCost)
	mux.HandleFunc("/cost/fleet", handlers.GetFleetCost)
	mux.HandleFunc("/cost/summary", handlers.GetCostSummary)
	mux.HandleFunc("/cost/comparison", handlers.GetCostComparison)
	mux.HandleFunc("/cost/report", handlers.GetReport)

	// Start health check server
	healthServer := &health.HealthCheckServer{}
	go healthServer.Serve(nil)

	// Start HTTP server
	port := envtool.GetEnv("PORT", "8077")
	logger.Info().Msgf("Cost service listening on http://0.0.0.0:%s", port)
	if err := http.ListenAndServe(":"+port, mux); err != nil {
		logger.Fatal().Err(err).Msg("Failed to start server")
	}
}
