package iam

import (
	"errors"
	"net/http"
	"strings"

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

func (s *Service) RequireAccess() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := extractBearerToken(c.GetHeader("Authorization"))
		if token == "" {
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "missing authorization"})
			return
		}
		claims, err := s.ValidateAccessToken(c.Request.Context(), token)
		if err != nil {
			status := http.StatusUnauthorized
			if errors.Is(err, errSessionRevoked) {
				status = http.StatusUnauthorized
			}
			c.AbortWithStatusJSON(status, gin.H{"error": "invalid token"})
			return
		}
		c.Set(ContextUserIDKey, claims.UserID)
		c.Set(ContextSessionIDKey, claims.SessionID)
		c.Set(ContextJTIKey, claims.JTI)
		c.Next()
	}
}

func extractBearerToken(header string) string {
	authHeader := strings.TrimSpace(header)
	if strings.HasPrefix(authHeader, "Bearer ") {
		return strings.TrimSpace(authHeader[7:])
	}
	return authHeader
}
