package usecase

import (
	"testing"

	"apps/backend/internal/module/radar/domain"
)

func TestBuildQueryPlanUsesDemandAndCapsGroups(t *testing.T) {
	m := &domain.DemandMap{
		ProductID: "p1", DemandInputVersion: "demand-a", MapVersion: 3, State: "ready",
		PainPhrases:      []domain.DemandMapPhrase{{Text: "泛紅不適", Kind: "pain", BasisText: "泛紅不適", Enabled: true}, {Text: "舒緩精華", Kind: "pain", Enabled: true}},
		ScenarioPhrases:  []domain.DemandMapPhrase{{Text: "換季", Kind: "scenario", Enabled: true}},
		DesiredOutcomes:  []domain.DemandMapPhrase{{Text: "舒緩", Kind: "outcome", Enabled: true}},
		SolutionSignals:  []domain.DemandMapPhrase{{Text: "修護", Kind: "solution", Enabled: true}},
		ExclusionSignals: []domain.DemandMapPhrase{{Text: "團購", Kind: "exclusion", Enabled: true}},
	}
	plan, err := BuildQueryPlan(m, "舒緩精華")
	if err != nil {
		t.Fatal(err)
	}
	if len(plan.Groups) == 0 || len(plan.Groups) > domain.MaxExploreTerms {
		t.Fatalf("unexpected group count: %d", len(plan.Groups))
	}
	for _, group := range plan.Groups {
		if group.Query == "舒緩精華" || !domain.IsThreadsSearchable(group.Query) {
			t.Fatalf("invalid product-only/long query: %+v", group)
		}
		if len(group.Exclude) != 1 || group.Exclude[0] != "團購" {
			t.Fatalf("exclusions not carried: %+v", group)
		}
	}
}

func TestBuildQueryPlanRejectsIncomplete(t *testing.T) {
	_, err := BuildQueryPlan(&domain.DemandMap{State: "incomplete"}, "")
	if err == nil {
		t.Fatal("incomplete map must not produce a plan")
	}
}

func TestBuildQueryPlanShortensLongDemandPhrases(t *testing.T) {
	m := &domain.DemandMap{
		ProductID: "p1", DemandInputVersion: "demand-a", MapVersion: 1, State: "ready",
		PainPhrases:     []domain.DemandMapPhrase{{Text: "晚上睡覺容易口乾舌燥怎麼辦", Kind: "pain", Enabled: true}},
		ScenarioPhrases: []domain.DemandMapPhrase{{Text: "換季日常修護", Kind: "scenario", Enabled: true}},
		SolutionSignals: []domain.DemandMapPhrase{{Text: "保濕", Kind: "solution", Enabled: true}},
	}
	plan, err := BuildQueryPlan(m, "舒緩精華")
	if err != nil {
		t.Fatal(err)
	}
	if len(plan.Groups) == 0 {
		t.Fatal("long demand phrases must still compile into a plan")
	}
	for _, group := range plan.Groups {
		if !domain.IsThreadsSearchable(group.Query) {
			t.Fatalf("unsearchable query: %+v", group)
		}
	}
}
