package integration_test

import (
	"context"
	"strings"
	"testing"
	"time"

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

// TestUserAccount_GetThroughGatewayEdge drives the authenticated
// edge user surface (`user.account.get`) through gateway → backend
// → user store. The test signs an envelope, sends it via Connect, and
// verifies the response signature, then decodes the FlatBuffers
// payload into the typed AccountResponse.
//
// Side effect: the gateway also sets `X-User-ID` and forwards to
// backend's HTTP `/api/v1/user/account`, which triggers the geo
// counter middleware. We validate the counter increments on the
// admin geo endpoint.
func TestUserAccount_GetThroughGatewayEdge(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+account@example.com")

	gw, err := sess.DialAuthenticated(ctx, plat)
	if err != nil {
		t.Fatalf("dial gateway: %v", err)
	}
	defer gw.Close()

	payload, err := transcoder.GetMyAccountRequestToPayload(&usermodel.GetMyAccountRequest{})
	if err != nil {
		t.Fatalf("encode get-account payload: %v", err)
	}

	res, err := gw.Execute(ctx, usermodel.MessageTypeGetMyAccount, payload, testenv.ExecuteOptions{})
	if err != nil {
		t.Fatalf("execute get-account: %v", err)
	}
	if res.ResultCode != "ok" {
		t.Fatalf("expected ok result_code, got %q", res.ResultCode)
	}

	got, err := transcoder.PayloadToAccountResponse(res.PayloadBytes)
	if err != nil {
		t.Fatalf("decode account response: %v", err)
	}
	if got.Account.UserID == "" {
		t.Fatalf("decoded account missing user_id")
	}
	if got.Account.Email != sess.Email {
		t.Fatalf("decoded account email = %q, want %q", got.Account.Email, sess.Email)
	}
	if !strings.HasPrefix(got.Account.UserName, "Player-") && !strings.HasPrefix(strings.ToLower(got.Account.UserName), "player-") {
		t.Fatalf("user_name = %q, want Player-XXXXXXXX shape", got.Account.UserName)
	}
}
