package middleware

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

var roleLevels = map[string]int{
	"user":      0,
	"moderator": 1,
	"admin":     2,
	"owner":     3,
}

// RequireRole enforces a minimum role: owner > admin > moderator > user.
func RequireRole(minRole string) fiber.Handler {
	minLevel := roleLevels[minRole]

	return func(c *fiber.Ctx) error {
		role, ok := c.Locals("role").(string)
		if !ok {
			return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
				"error": "Authentication required",
			})
		}

		userLevel := roleLevels[role]
		if userLevel < minLevel {
			return c.Status(fiber.StatusForbidden).JSON(fiber.Map{
				"error": "Insufficient permissions. Required role: " + minRole,
			})
		}

		return c.Next()
	}
}

func RequireExactRole(role string) fiber.Handler {
	return func(c *fiber.Ctx) error {
		userRole, ok := c.Locals("role").(string)
		if !ok || userRole != role {
			return c.Status(fiber.StatusForbidden).JSON(fiber.Map{
				"error": "This action requires the '" + role + "' role",
			})
		}
		return c.Next()
	}
}
