package fullservernotice

import (
	"strings"
	"testing"
)

func TestBuildFanoutJSONForUserIDScope(t *testing.T) {
	req, err := normalizeFanoutRequest(fanoutRequest{
		MessageType: "activity",
		TargetScope: "user_ids",
		UserIDs:     int64List{42, 43, 42, 0},
		Title:       "活动上线",
		Summary:     "新活动已上线。",
		Actions: []inboxActionRequest{{
			Action: " JOIN ",
			Label:  " Join now ",
			Style:  " PRIMARY ",
			API: inboxActionAPIRequest{
				Method: " post ",
				Path:   " /api/v1/activities/act_01/join ",
				Body:   map[string]any{"campaign_id": "act_01"},
			},
		}},
		ActionType:   "activity_detail",
		ActionParam:  "activity_id=act_01",
		MetadataJSON: `{"source":"admin"}`,
		BatchSize:    500,
	}, 1)
	if err != nil {
		t.Fatalf("normalizeFanoutRequest failed: %v", err)
	}
	targetFilterJSON, err := buildTargetFilterJSON(req)
	if err != nil {
		t.Fatalf("buildTargetFilterJSON failed: %v", err)
	}
	if targetFilterJSON != `{"user_ids":[42,43]}` {
		t.Fatalf("target filter mismatch: %s", targetFilterJSON)
	}
	templateSnapshotJSON, err := buildTemplateSnapshotJSON(req)
	if err != nil {
		t.Fatalf("buildTemplateSnapshotJSON failed: %v", err)
	}
	for _, required := range []string{`"title":"活动上线"`, `"action":"join"`, `"label":"Join now"`, `"method":"POST"`, `"path":"/api/v1/activities/act_01/join"`, `"action_type":"activity_detail"`, `"metadata_json":{"source":"admin"}`} {
		if !strings.Contains(templateSnapshotJSON, required) {
			t.Fatalf("template snapshot %s missing %s", templateSnapshotJSON, required)
		}
	}
}

func TestFanoutUserIDsAcceptNumericStrings(t *testing.T) {
	var userIDs int64List
	if err := userIDs.UnmarshalJSON([]byte(`["325379237278126080","42"]`)); err != nil {
		t.Fatalf("UnmarshalJSON failed: %v", err)
	}
	if len(userIDs) != 2 || userIDs[0] != 325379237278126080 || userIDs[1] != 42 {
		t.Fatalf("user_ids mismatch: %+v", userIDs)
	}
}

func TestNormalizeFanoutRequestRequiresTargetParameters(t *testing.T) {
	req, err := normalizeFanoutRequest(fanoutRequest{
		MessageType: "system",
		TargetScope: "country",
		Title:       "维护通知",
		Summary:     "今晚维护。",
		BatchSize:   500,
	}, 1)
	if err != nil {
		t.Fatalf("normalizeFanoutRequest failed: %v", err)
	}
	if _, err := buildTargetFilterJSON(req); err == nil {
		t.Fatalf("country target without country should fail")
	}
}

func TestBuildFanoutJSONForAllRegisteredUsersScope(t *testing.T) {
	req, err := normalizeFanoutRequest(fanoutRequest{
		MessageType: "system",
		TargetScope: "all_registered_users",
		Title:       "系统通知",
		Summary:     "所有注册用户可见。",
		BatchSize:   500,
	}, 1)
	if err != nil {
		t.Fatalf("normalizeFanoutRequest failed: %v", err)
	}
	targetFilterJSON, err := buildTargetFilterJSON(req)
	if err != nil {
		t.Fatalf("buildTargetFilterJSON failed: %v", err)
	}
	if targetFilterJSON != `{}` {
		t.Fatalf("target filter mismatch: %s", targetFilterJSON)
	}
}
