package platform

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

	keyring "github.com/zalando/go-keyring"
)

// A session whose name is still the subject UUID (minted by an older build) heals from
// /api/me — name + avatar corrected and re-persisted, so later launches are correct without
// any further /api/me.
func TestHealIdentity_StaleNameHealed(t *testing.T) {
	keyring.MockInit()
	dir := t.TempDir()
	t.Setenv("XDG_CONFIG_HOME", dir)
	t.Setenv("HOME", dir)

	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path == "/api/me" {
			_ = json.NewEncoder(w).Encode(map[string]any{
				"user_id": "sub-1", "name": "Commilitia", "avatar": "https://a.net/x.png",
			})
			return
		}
		w.WriteHeader(http.StatusNotFound)
	}))
	defer srv.Close()

	s := &LoginResult{
		AccessToken: "acc", RefreshToken: "rtk", ExpiresIn: 900,
		User: UserInfo{ID: "sub-1", Name: "sub-1"}, // stale: name == subject UUID
	}
	out := HealIdentity(s, srv.URL)
	if out.User.Name != "Commilitia" {
		t.Errorf("name: got %q, want Commilitia", out.User.Name)
	}
	if out.User.Avatar != "https://a.net/x.png" {
		t.Errorf("avatar: got %q, want the /api/me avatar", out.User.Avatar)
	}
	loaded, err := LoadSession()
	if err != nil || loaded == nil || loaded.User.Name != "Commilitia" || loaded.User.Avatar != "https://a.net/x.png" {
		t.Errorf("heal not persisted: %+v (err %v)", loaded, err)
	}
}

// A session that already has a real display name is left untouched and never hits /api/me.
func TestHealIdentity_HealthyNameSkips(t *testing.T) {
	called := false
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		called = true
		w.WriteHeader(http.StatusNotFound)
	}))
	defer srv.Close()

	s := &LoginResult{AccessToken: "acc", User: UserInfo{ID: "sub-1", Name: "Commilitia"}}
	out := HealIdentity(s, srv.URL)
	if called {
		t.Error("a healthy identity must skip the /api/me round-trip")
	}
	if out.User.Name != "Commilitia" {
		t.Errorf("name changed unexpectedly: %q", out.User.Name)
	}
}
