package transcode_test

import (
	"context"
	"net/http"
	"testing"

	"scrabble/gateway/internal/transcode"
	fb "scrabble/pkg/fbs/scrabblefb"
)

// TestProfileGetEncodesAds verifies the gateway forwards the backend's interstitial-ad block
// into the Profile payload: the three cooldowns and the suppressed flag the client-mirrored gate
// reads. The encode is not exercised by the mock e2e (it bypasses the codec), so a dropped field
// would only surface here.
func TestProfileGetEncodesAds(t *testing.T) {
	backend, cleanup := fakeBackend(t, func(w http.ResponseWriter, r *http.Request) {
		if r.Method != http.MethodGet || r.URL.Path != "/api/v1/user/profile" {
			t.Errorf("unexpected %s %q", r.Method, r.URL.Path)
		}
		_, _ = w.Write([]byte(`{"user_id":"u-1","display_name":"Kaya","preferred_language":"en",` +
			`"ads":{"cooldown_global_s":300,"cooldown_vs_ai_s":1800,"cooldown_hint_s":60,"suppressed":true}}`))
	})
	defer cleanup()

	reg := transcode.NewRegistry(backend, nil)
	op, ok := reg.Lookup(transcode.MsgProfileGet)
	if !ok {
		t.Fatal("profile.get not registered")
	}
	payload, err := op.Handler(context.Background(), transcode.Request{UserID: "u-1"})
	if err != nil {
		t.Fatalf("handler: %v", err)
	}

	ads := fb.GetRootAsProfile(payload, 0).Ads(nil)
	if ads == nil {
		t.Fatal("profile carries no ads block")
	}
	if ads.CooldownGlobalS() != 300 || ads.CooldownVsAiS() != 1800 || ads.CooldownHintS() != 60 {
		t.Errorf("cooldowns = %d/%d/%d, want 300/1800/60", ads.CooldownGlobalS(), ads.CooldownVsAiS(), ads.CooldownHintS())
	}
	if !ads.Suppressed() {
		t.Error("suppressed = false, want true")
	}
}

// TestProfileGetNoAds verifies a profile without an ads block encodes none (the backend omits it
// only on an internal failure; normally the block is always present).
func TestProfileGetNoAds(t *testing.T) {
	backend, cleanup := fakeBackend(t, func(w http.ResponseWriter, r *http.Request) {
		_, _ = w.Write([]byte(`{"user_id":"u-1","display_name":"Kaya","preferred_language":"en"}`))
	})
	defer cleanup()

	reg := transcode.NewRegistry(backend, nil)
	op, _ := reg.Lookup(transcode.MsgProfileGet)
	payload, err := op.Handler(context.Background(), transcode.Request{UserID: "u-1"})
	if err != nil {
		t.Fatalf("handler: %v", err)
	}
	if p := fb.GetRootAsProfile(payload, 0); p.Ads(nil) != nil {
		t.Error("profile without an ads block unexpectedly carries one")
	}
}
