package middleware

import (
	"git.ma-al.com/goc_daniel/b2b/app/delivery/middleware/perms"
	"git.ma-al.com/goc_daniel/b2b/app/model"
	"github.com/gofiber/fiber/v3"
)

func Require(p perms.Permission) fiber.Handler {
	return func(c fiber.Ctx) error {
		u := c.Locals("user")
		if u == nil {
			return c.SendStatus(fiber.StatusUnauthorized)
		}

		user, ok := u.(*model.UserSession)
		if !ok {
			return c.SendStatus(fiber.StatusInternalServerError)
		}

		for _, perm := range user.Permissions {
			if perm == p {
				return c.Next()
			}
		}
		return c.SendStatus(fiber.StatusForbidden)
	}
}
