package middlewares

import (
	"strings"

	"goFiber/services"

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

const authClaimsKey = "auth_claims"

func RequireAuth(c fiber.Ctx) error {
	authHeader := strings.TrimSpace(c.Get("Authorization"))
	if authHeader == "" {
		return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error": "authorization header is required"})
	}

	parts := strings.SplitN(authHeader, " ", 2)
	if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") || strings.TrimSpace(parts[1]) == "" {
		return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error": "invalid authorization format, expected: Bearer <token>"})
	}

	jwtService := services.NewJWTService()
	claims, err := jwtService.ValidateToken(strings.TrimSpace(parts[1]))
	if err != nil {
		return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error": "invalid token"})
	}
	if claims.TokenType != services.TokenTypeAccess {
		return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error": "access token required"})
	}

	c.Locals(authClaimsKey, claims)
	return c.Next()
}

func RequireAdmin(c fiber.Ctx) error {
	claims, ok := GetAuthClaims(c)
	if !ok {
		return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error": "unauthorized"})
	}
	if !claims.IsAdmin {
		return c.Status(fiber.StatusForbidden).JSON(fiber.Map{"error": "admin role required"})
	}
	return c.Next()
}

func RequireNormalUser(c fiber.Ctx) error {
	claims, ok := GetAuthClaims(c)
	if !ok {
		return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error": "unauthorized"})
	}
	if claims.IsAdmin {
		return c.Status(fiber.StatusForbidden).JSON(fiber.Map{"error": "only normal users can access this endpoint"})
	}
	return c.Next()
}

func GetAuthClaims(c fiber.Ctx) (*services.JWTClaim, bool) {
	raw := c.Locals(authClaimsKey)
	claims, ok := raw.(*services.JWTClaim)
	return claims, ok
}
