package main

import (
	"log"
	"solacenet-gateway/cache"
	"solacenet-gateway/config"
	"solacenet-gateway/handlers"
	"solacenet-gateway/middleware"

	"github.com/gin-gonic/gin"
)

func main() {
	cfg := config.Load()

	// Initialize Redis cache
	redisCache, err := cache.New(cfg.RedisURL)
	if err != nil {
		log.Printf("Warning: Redis not available, caching disabled: %v", err)
		redisCache = nil
	}
	defer func() {
		if redisCache != nil {
			redisCache.Close()
		}
	}()

	// Set up Gin router
	if cfg.LogLevel == "production" {
		gin.SetMode(gin.ReleaseMode)
	}

	router := gin.Default()

	// Middleware
	router.Use(middleware.AuthMiddleware(cfg))
	if redisCache != nil {
		router.Use(middleware.CapabilityCheckMiddleware(cfg, redisCache))
	}
	router.Use(middleware.RateLimitMiddleware())

	// Health check
	router.GET("/health", handlers.HealthHandler)

	// Proxy handler for backend services
	router.Any("/api/*path", handlers.ProxyHandler(cfg))

	// Start server
	log.Printf("SolaceNet Gateway starting on port %s", cfg.Port)
	if err := router.Run(":" + cfg.Port); err != nil {
		log.Fatal("Failed to start server:", err)
	}
}
