package main

import (
	"log"
	"net/http"
	"tankstopp/internal/config"
	"tankstopp/internal/database"
	"tankstopp/internal/handlers"

	"github.com/gorilla/mux"
)

func main() {
	// Load configuration from file and environment variables
	configPath := config.GetConfigFromEnv()
	cfg, err := config.Load(configPath)
	if err != nil {
		log.Printf("Warning: Failed to load config file '%s': %v", configPath, err)
		log.Println("Falling back to environment variables and defaults...")

		// Fallback to environment-based configuration
		db, err := database.NewDBFromEnv()
		if err != nil {
			log.Fatal("Failed to connect to database:", err)
		}
		defer db.Close()

		log.Println("Database connection established with GORM (using environment config)")

		// Initialize handlers
		h := handlers.NewHandler(db)

		// Create router
		r := mux.NewRouter()

		// Register all routes
		h.RegisterRoutes(r)

		// Start server with default settings
		log.Println("Server starting on :8081")
		log.Println("Visit http://localhost:8081 to access the application")
		log.Fatal(http.ListenAndServe(":8081", r))
		return
	}

	log.Printf("Loaded configuration from: %s", configPath)
	log.Printf("Configuration: %s", cfg.String())

	// Initialize database with Viper configuration
	db, err := database.NewDBFromConfig(configPath)
	if err != nil {
		log.Fatal("Failed to connect to database:", err)
	}
	defer db.Close()

	log.Println("Database connection established with GORM")

	// Initialize handlers
	h := handlers.NewHandler(db)

	// Create router
	r := mux.NewRouter()

	// Register all routes
	h.RegisterRoutes(r)

	// Create server with configuration
	server := &http.Server{
		Addr:         cfg.GetServerAddress(),
		Handler:      r,
		ReadTimeout:  cfg.Server.ReadTimeout,
		WriteTimeout: cfg.Server.WriteTimeout,
		IdleTimeout:  cfg.Server.IdleTimeout,
	}

	// Start server
	log.Printf("Server starting on %s", cfg.GetServerAddress())
	log.Printf("Environment: %s", cfg.App.Environment)
	log.Printf("Debug mode: %t", cfg.App.Debug)
	log.Printf("Visit http://%s to access the application", cfg.GetServerAddress())

	if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
		log.Fatal("Server failed to start:", err)
	}
}
