package usecase

import (
	"strings"
	"testing"

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

func productFitSnapshot() *ProductContextSnapshot {
	return &ProductContextSnapshot{
		BrandID: "b1", ProductID: "p1", BrandName: "清透品牌", ProductLabel: "溫和保養",
		TargetAudience: "敏感肌", PainPoints: []string{"泛紅不適"},
		MatchTags: []string{"換季保養"}, ProductContext: "換季保養",
		ProviderCapabilityTerms: []string{"舒緩修護"}, ProviderExcludeTerms: []string{"徵才"},
	}
}

func TestScoreProductFitDimensionBoundaries(t *testing.T) {
	tests := []struct {
		name          string
		text          string
		want          int
		band          string
		eligible      bool
		wantDimension string
	}{
		{"pain only", "我最近泛紅不適，想問怎麼辦", 35, domain.ProductFitBandWeak, false, domain.ProductFitPain},
		{"pain scenario", "換季保養時泛紅不適，想找舒緩修護", 80, domain.ProductFitBandStrong, true, domain.ProductFitPain},
		{"all dimensions", "敏感肌換季保養泛紅不適，想找舒緩修護", 100, domain.ProductFitBandStrong, true, domain.ProductFitAudience},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			match, err := ScoreProductFit(&domain.CandidatePost{Text: tt.text}, productFitSnapshot())
			if err != nil {
				t.Fatal(err)
			}
			if match.ProductFitScore != tt.want || match.ProductFitBand != tt.band || match.Eligible != tt.eligible {
				t.Fatalf("score=%d band=%s eligible=%v, want %d/%s/%v; %+v", match.ProductFitScore, match.ProductFitBand, match.Eligible, tt.want, tt.band, tt.eligible, match)
			}
			for _, reason := range match.Reasons {
				if reason.Dimension == tt.wantDimension && reason.Score > 0 {
					if !strings.Contains(tt.text, reason.CandidateExcerpt) || reason.ProductBasis == "" {
						t.Fatalf("positive reason lacks source evidence: %+v", reason)
					}
				}
			}
		})
	}
}

func TestScoreProductFitNameOnlyAndUnknownAudience(t *testing.T) {
	p := productFitSnapshot()
	nameOnly, err := ScoreProductFit(&domain.CandidatePost{Text: "有人用過溫和保養嗎？"}, p)
	if err != nil {
		t.Fatal(err)
	}
	if nameOnly.ProductFitScore != 0 || nameOnly.Eligible || !strings.Contains(strings.Join(nameOnly.Risks, " "), "名稱") {
		t.Fatalf("name-only candidate was treated as demand: %+v", nameOnly)
	}
	unknownAudience, err := ScoreProductFit(&domain.CandidatePost{Text: "我有泛紅不適，想找換季保養"}, p)
	if err != nil {
		t.Fatal(err)
	}
	for _, reason := range unknownAudience.Reasons {
		if reason.Dimension == domain.ProductFitAudience && reason.Score != 0 {
			t.Fatalf("audience guessed from unknown text: %+v", reason)
		}
	}
}

func TestScoreProductFitExcludeHasReasonAndIsIneligible(t *testing.T) {
	match, err := ScoreProductFit(&domain.CandidatePost{Text: "徵才：找人一起做舒緩修護", Classification: "provider_offer"}, productFitSnapshot())
	if err != nil {
		t.Fatal(err)
	}
	if !match.Excluded || match.ExcludeReason == "" || match.Eligible {
		t.Fatalf("exclude guard missing: %+v", match)
	}
	if err := match.ValidateForWrite(); err != nil {
		t.Fatalf("excluded match should still validate: %v", err)
	}
}
