package middlewares

import (
	"gauth-central/config"
	"gauth-central/internal/services"
	"log"
	"net/http"

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

// DynamicCorsMiddleware - Database'den okunan CORS ayarlarıyla çalışan middleware
func DynamicCorsMiddleware(settingsService *services.SettingsService) gin.HandlerFunc {
	return func(c *gin.Context) {
		origin := c.Request.Header.Get("Origin")

		// If no origin header, skip CORS
		if origin == "" {
			c.Next()
			return
		}

		allowed, matchedEntry, matchedList, err := settingsService.CheckOrigin(origin)
		if config.AppConfig != nil && config.AppConfig.CorsDebug {
			log.Printf("cors_debug origin=%q allowed=%t matched_entry=%q matched_list=%q ip=%q", origin, allowed, matchedEntry, matchedList, c.ClientIP())
		}
		if err != nil {
			// On error, log and deny
			c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{
				"error": "Failed to verify CORS policy",
			})
			return
		}

		if !allowed {
			c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
				"error": "Origin not allowed by CORS policy",
			})
			return
		}

		// Set CORS headers
		c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
		c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
		c.Writer.Header().Set("Access-Control-Allow-Headers", "Origin, Content-Type, Accept, Authorization")
		c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")
		c.Writer.Header().Set("Access-Control-Max-Age", "86400") // 24 hours

		// Handle preflight requests
		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
			return
		}

		c.Next()
	}
}
