package middleware

import (
	"web-qudo-be/app/database/entity/users"
	"web-qudo-be/app/module/users/repository"
	utilSvc "web-qudo-be/utils/service"

	"github.com/gofiber/fiber/v2"
	"github.com/rs/zerolog"
)

const (
	UserContextKey      = "user"
	UserLevelContextKey = "user_level_id"
)

// UserMiddleware extracts user information from JWT token and stores in context
func UserMiddleware(usersRepo repository.UsersRepository) fiber.Handler {
	return func(c *fiber.Ctx) error {
		// Skip if no Authorization header
		authHeader := c.Get("Authorization")
		if authHeader == "" {
			return c.Next()
		}

		// Get user info from token
		// Create a default logger if not available in context
		log := zerolog.Nop()
		if logFromCtx, ok := c.Locals("log").(zerolog.Logger); ok {
			log = logFromCtx
		}
		user := utilSvc.GetUserInfo(log, usersRepo, authHeader)
		if user != nil {
			// Store user in context
			c.Locals(UserContextKey, user)
			c.Locals(UserLevelContextKey, user.UserLevelId)
		}

		return c.Next()
	}
}

// GetUser retrieves the user from the context
func GetUser(c *fiber.Ctx) *users.Users {
	if user, ok := c.Locals(UserContextKey).(*users.Users); ok {
		return user
	}
	return nil
}

// GetUserLevelID retrieves the user level ID from the context
func GetUserLevelID(c *fiber.Ctx) *uint {
	if userLevelId, ok := c.Locals(UserLevelContextKey).(uint); ok {
		return &userLevelId
	}
	return nil
}
