package main

import (
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestAuthMiddlewareAlt(t *testing.T) {
	// Test missing JWT header
	t.Run("Missing JWT", func(t *testing.T) {
		req := httptest.NewRequest("GET", "/api/libraries/visible", nil)
		rr := httptest.NewRecorder()

		// Simulate auth middleware
		handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			authHeader := r.Header.Get("Authorization")
			if authHeader == "" || !strings.HasPrefix(authHeader, "Bearer ") {
				w.WriteHeader(http.StatusUnauthorized)
				w.Write([]byte(`{"message":"missing or malformed jwt"}`))
				return
			}

			w.WriteHeader(http.StatusOK)
			w.Write([]byte(`{"message":"valid token"}`))
		})

		handler.ServeHTTP(rr, req)

		assert.Equal(t, http.StatusUnauthorized, rr.Code)
		assert.Equal(t, `{"message":"missing or malformed jwt"}`, rr.Body.String())
	})

	// Test invalid JWT token format
	t.Run("Invalid JWT format", func(t *testing.T) {
		req := httptest.NewRequest("GET", "/api/libraries/visible", nil)
		req.Header.Set("Authorization", "invalid-token")
		rr := httptest.NewRecorder()

		handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			authHeader := r.Header.Get("Authorization")
			if authHeader == "" || !strings.HasPrefix(authHeader, "Bearer ") {
				w.WriteHeader(http.StatusUnauthorized)
				w.Write([]byte(`{"message":"missing or malformed jwt"}`))
				return
			}

			w.WriteHeader(http.StatusOK)
			w.Write([]byte(`{"message":"valid token"}`))
		})

		handler.ServeHTTP(rr, req)

		assert.Equal(t, http.StatusUnauthorized, rr.Code)
		assert.Equal(t, `{"message":"missing or malformed jwt"}`, rr.Body.String())
	})

	// Test valid JWT token format
	t.Run("Valid JWT format", func(t *testing.T) {
		req := httptest.NewRequest("GET", "/api/libraries/visible", nil)
		req.Header.Set("Authorization", "Bearer valid-token")
		rr := httptest.NewRecorder()

		handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			authHeader := r.Header.Get("Authorization")
			if authHeader == "" || !strings.HasPrefix(authHeader, "Bearer ") {
				w.WriteHeader(http.StatusUnauthorized)
				w.Write([]byte(`{"message":"missing or malformed jwt"}`))
				return
			}

			w.WriteHeader(http.StatusOK)
			w.Write([]byte(`{"message":"valid token"}`))
		})

		handler.ServeHTTP(rr, req)

		assert.Equal(t, http.StatusOK, rr.Code)
		assert.Equal(t, `{"message":"valid token"}`, rr.Body.String())
	})
}
