package authentik

import (
	"context"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"testing"
)

func TestSetUserAvatarAttribute(t *testing.T) {
	const userUUID = "11111111-1111-1111-1111-111111111111"
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		switch {
		case r.Method == http.MethodGet && r.URL.Path == "/api/v3/core/users/":
			_ = json.NewEncoder(w).Encode(listResponse[akUser]{
				Results: []akUser{{
					PK:   42,
					UUID: userUUID,
					Attributes: map[string]any{
						"phone": "+33123456789",
					},
				}},
			})
		case r.Method == http.MethodPatch && r.URL.Path == "/api/v3/core/users/42/":
			var body map[string]any
			if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
				t.Fatalf("decode patch body: %v", err)
			}
			attrs, ok := body["attributes"].(map[string]any)
			if !ok {
				t.Fatalf("attributes = %#v", body["attributes"])
			}
			if attrs["phone"] != "+33123456789" {
				t.Fatalf("phone not preserved: %#v", attrs["phone"])
			}
			if attrs["avatar"] != "data:image/png;base64,abc" {
				t.Fatalf("avatar = %#v", attrs["avatar"])
			}
			w.WriteHeader(http.StatusOK)
		default:
			t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
		}
	}))
	defer srv.Close()

	client := NewClient(srv.URL, "token")
	if err := client.SetUserAvatarAttribute(context.Background(), userUUID, "data:image/png;base64,abc"); err != nil {
		t.Fatalf("SetUserAvatarAttribute() error = %v", err)
	}
}

func TestGetUserAvatarAttribute(t *testing.T) {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		_ = json.NewEncoder(w).Encode(listResponse[akUser]{
			Results: []akUser{{
				PK: 7,
				Attributes: map[string]any{
					"avatar": " data:image/jpeg;base64,xyz ",
				},
			}},
		})
	}))
	defer srv.Close()

	client := NewClient(srv.URL, "token")
	got, err := client.GetUserAvatarAttribute(context.Background(), "uuid")
	if err != nil {
		t.Fatalf("GetUserAvatarAttribute() error = %v", err)
	}
	if got != "data:image/jpeg;base64,xyz" {
		t.Fatalf("GetUserAvatarAttribute() = %q", got)
	}
}
