package hostorg

import (
	"encoding/json"
	"testing"
)

func TestFlexibleInt64AcceptsStringAndNumber(t *testing.T) {
	t.Parallel()
	cases := []struct {
		name string
		body string
		want int64
	}{
		{name: "string", body: `{"targetUserId":"323096761415507968"}`, want: 323096761415507968},
		{name: "number", body: `{"targetUserId":323096761415507968}`, want: 323096761415507968},
	}
	for _, tc := range cases {
		tc := tc
		t.Run(tc.name, func(t *testing.T) {
			t.Parallel()
			var req createBDLeaderRequest
			if err := json.Unmarshal([]byte(tc.body), &req); err != nil {
				t.Fatalf("unmarshal request: %v", err)
			}
			if got := req.TargetUserID.Int64(); got != tc.want {
				t.Fatalf("target user id = %d, want %d", got, tc.want)
			}
		})
	}
}

func TestManagerCrossRegionDefaultsClosedAndAcceptsLegacyField(t *testing.T) {
	var omitted createManagerRequest
	if err := json.Unmarshal([]byte(`{"targetUserId":"1003"}`), &omitted); err != nil {
		t.Fatalf("unmarshal omitted permission: %v", err)
	}
	if omitted.permissionsWithDefault().CanManageCrossRegion {
		t.Fatalf("cross-region manager must default closed")
	}

	var enabled createManagerRequest
	if err := json.Unmarshal([]byte(`{"targetUserId":"1003","canManageCrossRegion":true}`), &enabled); err != nil {
		t.Fatalf("unmarshal enabled permission: %v", err)
	}
	if !enabled.permissionsWithDefault().CanManageCrossRegion {
		t.Fatalf("explicit cross-region permission must be preserved")
	}

	var legacy createManagerRequest
	if err := json.Unmarshal([]byte(`{"targetUserId":"1003","canAddBdLeaderInRegion":true}`), &legacy); err != nil {
		t.Fatalf("unmarshal legacy permission: %v", err)
	}
	if !legacy.permissionsWithDefault().CanManageCrossRegion {
		t.Fatalf("legacy region field must map to cross-region manager during rolling upgrade")
	}
}
