package middlewares

import (
	"doormile/config"
	"doormile/utils"

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

// WsChatAuth validates a JWT passed as a ?token= query parameter.
//
// WebSocket clients (both browsers and Flutter) cannot set the Authorization
// header during the initial HTTP upgrade handshake, so the token is sent as a
// query parameter instead. Fiber locals set here are forwarded into the
// WebSocket handler via the gofiber/websocket package.
func WsChatAuth(cfg *config.Config) fiber.Handler {
	return func(c *fiber.Ctx) error {
		token := c.Query("token")
		if token == "" {
			return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
				"error": "token query parameter is required",
			})
		}

		claims, err := utils.ParseToken(token, cfg.JWTSecret)
		if err != nil {
			return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
				"error": "invalid or expired token",
			})
		}

		c.Locals("userid", claims.UserID)
		c.Locals("roleid", claims.RoleID)
		return c.Next()
	}
}
