package middleware

import (
	"server/internal/tokens"

	"github.com/gofiber/fiber/v3"
	"gorm.io/gorm"
)

func GetAuthClaims(dbConn *gorm.DB, tokenService *tokens.TockenService) fiber.Handler {
	return func(c fiber.Ctx) error {
		tokenString := c.Get("Auth-Token")
		if tokenString == "" {
			// missing header
			return c.Next()
		}
		claims, err := tokenService.ValidateAccessToken(tokenString)
		if err != nil {
			// token not valid
			return c.Next()
		}
		// store claims
		c.Locals("authClaims", claims)
		return c.Next()
	}
}

func AuthMe(c fiber.Ctx) error {
	claims := c.Locals("authClaims")
	if claims == nil {
		return c.Status(fiber.StatusOK).JSON(fiber.Map{
			"authenticated": false,
		})
	}
	return c.Next()
}
