package middleware

import (
	"net/http"
	"strings"

	"github.com/acp/interceptor/internal/auth"
	"github.com/acp/interceptor/internal/tracing"
	"github.com/acp/interceptor/internal/utils"
	"github.com/gin-gonic/gin"
)

// JWTAuth validates Authorization: Bearer tokens when JWT is enabled.
func JWTAuth(v *auth.Validator) gin.HandlerFunc {
	if v == nil || !v.Enabled() {
		return func(c *gin.Context) {
			c.Next()
		}
	}

	return func(c *gin.Context) {
		// JWT governs tool execution only; health + insights APIs stay open for dashboard.
		if c.Request.URL.Path != "/tool-call" {
			c.Next()
			return
		}

		traceID := tracing.TraceIDFromContext(c)
		raw := strings.TrimSpace(c.GetHeader("Authorization"))
		token := ""
		if strings.HasPrefix(strings.ToLower(raw), "bearer ") {
			token = strings.TrimSpace(raw[7:])
		}

		principal, err := v.Validate(token)
		if err != nil {
			utils.AbortWithErrorJSON(c, http.StatusUnauthorized, traceID, err.Error())
			return
		}
		if principal != nil {
			auth.SetGinPrincipal(c, principal)
			ctx := auth.WithPrincipal(c.Request.Context(), principal)
			c.Request = c.Request.WithContext(ctx)
		}
		c.Next()
	}
}
