package transcode_test

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

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

// TestBlockStatusRoundTrip checks the account.block_status op forwards to the backend block-status
// endpoint and encodes its JSON into the BlockStatus FlatBuffer.
func TestBlockStatusRoundTrip(t *testing.T) {
	backend, cleanup := fakeBackend(t, func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path != "/api/v1/user/block-status" {
			t.Errorf("path = %q, want /api/v1/user/block-status", r.URL.Path)
		}
		_, _ = w.Write([]byte(`{"blocked":true,"permanent":false,"until":"2026-07-01T12:00:00Z","reason":"Спам"}`))
	})
	defer cleanup()

	reg := transcode.NewRegistry(backend, nil)
	op, ok := reg.Lookup(transcode.MsgBlockStatus)
	if !ok {
		t.Fatal("account.block_status not registered")
	}
	payload, err := op.Handler(context.Background(), transcode.Request{UserID: "u-1"})
	if err != nil {
		t.Fatalf("handler: %v", err)
	}
	bs := fb.GetRootAsBlockStatus(payload, 0)
	if !bs.Blocked() || bs.Permanent() {
		t.Fatalf("blocked=%v permanent=%v, want true/false", bs.Blocked(), bs.Permanent())
	}
	if string(bs.Until()) != "2026-07-01T12:00:00Z" {
		t.Errorf("until = %q, want the forwarded instant", bs.Until())
	}
	if string(bs.Reason()) != "Спам" {
		t.Errorf("reason = %q, want Спам", bs.Reason())
	}
}

// TestBlockedBackendSurfacesDomainCode checks that a backend 403 with code account_blocked (the
// suspension gate) surfaces as a domain code, which the Execute layer turns into the envelope
// result_code the UI keys off.
func TestBlockedBackendSurfacesDomainCode(t *testing.T) {
	backend, cleanup := fakeBackend(t, func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusForbidden)
		_, _ = w.Write([]byte(`{"error":{"code":"account_blocked","message":"account is blocked"}}`))
	})
	defer cleanup()

	reg := transcode.NewRegistry(backend, nil)
	op, _ := reg.Lookup(transcode.MsgProfileGet) // any gated op hits the same gate
	_, err := op.Handler(context.Background(), transcode.Request{UserID: "u-1"})
	if err == nil {
		t.Fatal("expected an error from a blocked backend response")
	}
	code, ok := transcode.DomainCode(err)
	if !ok || code != "account_blocked" {
		t.Fatalf("DomainCode = (%q, %v), want (account_blocked, true)", code, ok)
	}
}
