package middleware

import (
	"net/http"
	"strings"

	"kra/internal/conf"

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

const (
	defaultCORSHeaders = "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token,X-Token,X-User-Id"
	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 *conf.Runtime) gin.HandlerFunc {
	return func(c *gin.Context) {
		if runtime == nil {
			c.Next()
			return
		}
		config := runtime.Admin()
		if config == nil || config.Cors == nil {
			c.Next()
			return
		}
		mode := strings.TrimSpace(config.Cors.Mode)
		origin := c.GetHeader("Origin")
		corsHandled := false
		if mode == "allow-all" {
			if origin != "" {
				setCORSHeaders(c, origin, defaultCORSHeaders, defaultCORSMethods, defaultCORSExpose, true)
				corsHandled = true
			}
		} else if rule := matchingCORSRule(config.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 []*conf.AdminBackend_CORSRule, origin string) *conf.AdminBackend_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")
	}
}
