package middleware

import (
	"net/http"
	"strings"

	"kra/internal/config"

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

const (
	defaultCORSHeaders = "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token,X-Token"
	defaultCORSMethods = "POST, GET, OPTIONS,DELETE,PUT"
	defaultCORSExpose  = "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type, New-Token, New-Expires-At"
)

// CORS applies the current administration CORS rules on every request so a
// configuration reload takes effect without rebuilding the Gin engine.
func CORS(runtime *config.Store) gin.HandlerFunc {
	return func(c *gin.Context) {
		if runtime == nil {
			c.Next()
			return
		}
		snapshot := runtime.Snapshot()
		if snapshot == nil || snapshot.Admin == nil || snapshot.Admin.CORS == nil {
			c.Next()
			return
		}
		cors := snapshot.Admin.CORS
		mode := strings.TrimSpace(cors.Mode)
		origin := c.GetHeader("Origin")
		corsHandled := false
		if mode == "allow-all" {
			if origin != "" {
				setCORSHeaders(c, origin, defaultCORSHeaders, defaultCORSMethods, defaultCORSExpose, false)
				corsHandled = true
			}
		} else if rule := matchingCORSRule(cors.Whitelist, origin); rule != nil {
			setCORSHeaders(c, rule.AllowOrigin, rule.AllowHeaders, rule.AllowMethods, rule.ExposeHeaders, rule.AllowCredentials)
			corsHandled = true
		} else if mode == "strict-whitelist" && !(c.Request.Method == http.MethodGet && isHealthPath(c.Request.URL.Path)) {
			c.AbortWithStatus(http.StatusForbidden)
			return
		}
		if corsHandled && c.Request.Method == http.MethodOptions {
			c.AbortWithStatus(http.StatusNoContent)
			return
		}
		c.Next()
	}
}

func isHealthPath(path string) bool {
	path = strings.TrimSuffix(path, "/")
	return path == "/health" || strings.HasSuffix(path, "/health")
}

func matchingCORSRule(rules []*config.CORSRule, origin string) *config.CORSRule {
	for _, rule := range rules {
		if rule != nil && origin == rule.AllowOrigin {
			return rule
		}
	}
	return nil
}

func setCORSHeaders(c *gin.Context, origin, headers, methods, expose string, credentials bool) {
	c.Header("Vary", "Origin")
	c.Header("Access-Control-Allow-Origin", origin)
	c.Header("Access-Control-Allow-Headers", headers)
	c.Header("Access-Control-Allow-Methods", methods)
	c.Header("Access-Control-Expose-Headers", expose)
	if credentials {
		c.Header("Access-Control-Allow-Credentials", "true")
	}
}
