package middleware

import (
	"fmt"
	"net/http"

	"api-service/internal/config"

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

// ConfigurableAuthMiddleware provides flexible authentication based on configuration
func ConfigurableAuthMiddleware(cfg *config.Config) gin.HandlerFunc {
	return func(c *gin.Context) {
		// Skip authentication for development/testing if explicitly disabled
		if !cfg.Keycloak.Enabled {
			fmt.Println("Authentication is disabled - allowing all requests")
			c.Next()
			return
		}

		// Use Keycloak authentication when enabled
		AuthMiddleware()(c)
	}
}

// StrictAuthMiddleware enforces authentication regardless of Keycloak.Enabled setting
func StrictAuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		if appConfig == nil {
			fmt.Println("AuthMiddleware: Config not initialized")
			c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "authentication service not configured"})
			return
		}

		// Always enforce authentication
		AuthMiddleware()(c)
	}
}

// OptionalKeycloakAuthMiddleware allows requests but adds authentication info if available
func OptionalKeycloakAuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		if appConfig == nil || !appConfig.Keycloak.Enabled {
			c.Next()
			return
		}

		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			// No token provided, but continue
			c.Next()
			return
		}

		// Try to validate token, but don't fail if invalid
		AuthMiddleware()(c)
	}
}
