package middleware

import (
	"net/http"
	"strings"

	"erp-mvp/core-service/internal/auth"

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

type AuthMiddleware struct {
	jwtService *auth.JWTService
}

func NewAuthMiddleware(jwtService *auth.JWTService) *AuthMiddleware {
	return &AuthMiddleware{
		jwtService: jwtService,
	}
}

func (m *AuthMiddleware) AuthRequired() gin.HandlerFunc {
	return func(c *gin.Context) {
		// Получаем токен из заголовка Authorization
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "Authorization header required"})
			c.Abort()
			return
		}

		// Проверяем формат "Bearer <token>"
		tokenParts := strings.Split(authHeader, " ")
		if len(tokenParts) != 2 || tokenParts[0] != "Bearer" {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid authorization header format"})
			c.Abort()
			return
		}

		tokenString := tokenParts[1]

		// Валидируем токен
		claims, err := m.jwtService.ValidateToken(tokenString)
		if err != nil {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid token"})
			c.Abort()
			return
		}

		// Сохраняем claims в контексте
		c.Set("user_id", claims.UserID)
		c.Set("organization_id", claims.OrganizationID)
		c.Set("email", claims.Email)
		c.Set("role", claims.Role)

		c.Next()
	}
}

// GetClaims получает claims из контекста Gin
func GetClaims(c *gin.Context) *auth.Claims {
	userID, exists := c.Get("user_id")
	if !exists {
		return nil
	}

	orgID, exists := c.Get("organization_id")
	if !exists {
		return nil
	}

	email, exists := c.Get("email")
	if !exists {
		return nil
	}

	role, exists := c.Get("role")
	if !exists {
		return nil
	}

	return &auth.Claims{
		UserID:         userID.(uuid.UUID),
		OrganizationID: orgID.(uuid.UUID),
		Email:          email.(string),
		Role:           role.(string),
	}
}
