package main

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

	"scm.bstein.dev/bstein/Pegasus/backend/internal"
)

func TestLoginHandlerFailurePaths(t *testing.T) {
	um := &internal.UserMap{Map: map[string]internal.StringOrList{"brad": {"library"}}}
	jf := &fakeJellyfin{
		authErr: http.ErrNoCookie,
	}

	handler := loginHandler(um, jf)

	t.Run("bad json", func(t *testing.T) {
		rr := httptest.NewRecorder()
		handler.ServeHTTP(rr, httptest.NewRequest(http.MethodPost, "/api/login", bytes.NewBufferString("{bad")))
		if rr.Code != http.StatusBadRequest {
			t.Fatalf("expected bad json status, got %d", rr.Code)
		}
	})

	t.Run("invalid credentials", func(t *testing.T) {
		jf.authErr = http.ErrNoCookie
		rr := httptest.NewRecorder()
		handler.ServeHTTP(rr, requestWithCookie(http.MethodPost, "/api/login", "", []byte(`{"username":"brad","password":"bad"}`)))
		if rr.Code != http.StatusUnauthorized {
			t.Fatalf("expected unauthorized status, got %d", rr.Code)
		}
	})

	t.Run("missing mapping", func(t *testing.T) {
		jf.authErr = nil
		jf.authResult.AccessToken = "token"
		jf.authResult.User.Name = "brad"
		rr := httptest.NewRecorder()
		handler.ServeHTTP(rr, requestWithCookie(http.MethodPost, "/api/login", "", []byte(`{"username":"missing","password":"pw"}`)))
		if rr.Code != http.StatusForbidden {
			t.Fatalf("expected forbidden status, got %d", rr.Code)
		}
	})
}

func TestWhoamiHandlerFailurePaths(t *testing.T) {
	um := &internal.UserMap{Map: map[string]internal.StringOrList{"brad": {"library"}}}
	handler := whoamiHandler(um)

	t.Run("unauthorized", func(t *testing.T) {
		rr := httptest.NewRecorder()
		handler.ServeHTTP(rr, httptest.NewRequest(http.MethodGet, "/api/whoami", nil))
		if rr.Code != http.StatusUnauthorized {
			t.Fatalf("expected unauthorized status, got %d", rr.Code)
		}
	})

	t.Run("missing mapping", func(t *testing.T) {
		rr := httptest.NewRecorder()
		req := httptest.NewRequest(http.MethodGet, "/api/whoami", nil)
		cookie := sessionCookie(t, "missing", "token")
		req.Header.Set("Cookie", cookie)
		handler.ServeHTTP(rr, req)
		if rr.Code != http.StatusForbidden {
			t.Fatalf("expected forbidden status, got %d", rr.Code)
		}
	})
}
