package middlewares

import (
	"context"
	"net/http"
	"strings"

	"abuse_registration_poc/internal/handlers"
	"abuse_registration_poc/internal/utils"
)

type contextKey string

const (
	RoleContextKey   contextKey = "role"
	UserIDContextKey contextKey = "userId"
)

func Authenticate(next http.Handler) http.Handler {
	return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
		token := strings.TrimSpace(request.Header.Get("Authorization"))
		if token == "" {
			handlers.WriteJSON(writer, http.StatusUnauthorized, map[string]string{"message": "Not authorized."})
			return
		}
		token = strings.TrimPrefix(token, "Bearer ")

		userID, role, err := utils.VerifyToken(token)
		if err != nil {
			handlers.WriteJSON(writer, http.StatusUnauthorized, map[string]string{"message": "Not authorized."})
			return
		}

		ctx := context.WithValue(request.Context(), RoleContextKey, role)
		ctx = context.WithValue(ctx, UserIDContextKey, userID)
		next.ServeHTTP(writer, request.WithContext(ctx))
	})
}

func RoleFromContext(ctx context.Context) (string, bool) {
	role, ok := ctx.Value(RoleContextKey).(string)
	return role, ok
}
