package integration_test

import (
	"context"
	"testing"
	"time"

	"galaxy/integration/testenv"
	usermodel "galaxy/model/user"
	"galaxy/transcoder"
)

// TestUserProfileUpdate exercises `user.profile.update` over the
// authenticated edge surface (Connect / gRPC / gRPC-Web) and verifies that the new
// display_name is reflected by a subsequent `user.account.get`.
func TestUserProfileUpdate(t *testing.T) {
	plat := testenv.Bootstrap(t, testenv.BootstrapOptions{})
	ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
	defer cancel()

	sess := testenv.RegisterSession(t, plat, "pilot+profile@example.com")
	gw, err := sess.DialAuthenticated(ctx, plat)
	if err != nil {
		t.Fatalf("dial: %v", err)
	}
	defer gw.Close()

	const newName = "Captain Pilot"
	updatePayload, err := transcoder.UpdateMyProfileRequestToPayload(&usermodel.UpdateMyProfileRequest{
		DisplayName: newName,
	})
	if err != nil {
		t.Fatalf("encode update payload: %v", err)
	}
	res, err := gw.Execute(ctx, usermodel.MessageTypeUpdateMyProfile, updatePayload, testenv.ExecuteOptions{})
	if err != nil {
		t.Fatalf("execute update profile: %v", err)
	}
	if res.ResultCode != "ok" {
		t.Fatalf("update result_code = %q, want ok", res.ResultCode)
	}
	updated, err := transcoder.PayloadToAccountResponse(res.PayloadBytes)
	if err != nil {
		t.Fatalf("decode update response: %v", err)
	}
	if updated.Account.DisplayName != newName {
		t.Fatalf("update returned display_name = %q, want %q", updated.Account.DisplayName, newName)
	}

	// Re-fetch the account to confirm persistence.
	getPayload, err := transcoder.GetMyAccountRequestToPayload(&usermodel.GetMyAccountRequest{})
	if err != nil {
		t.Fatalf("encode get payload: %v", err)
	}
	gres, err := gw.Execute(ctx, usermodel.MessageTypeGetMyAccount, getPayload, testenv.ExecuteOptions{})
	if err != nil {
		t.Fatalf("execute get-account: %v", err)
	}
	got, err := transcoder.PayloadToAccountResponse(gres.PayloadBytes)
	if err != nil {
		t.Fatalf("decode get response: %v", err)
	}
	if got.Account.DisplayName != newName {
		t.Fatalf("re-fetched display_name = %q, want %q", got.Account.DisplayName, newName)
	}
}
