package usecase

import (
	"context"
	"testing"

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

func TestTodayExcludesWeakProductMatchesAndSupportsSelectedProduct(t *testing.T) {
	ctx := context.Background()
	svc := New(repository.NewMemory())
	weak := integrationOpportunity(42)
	weak.ID, weak.ExternalID = "weak", "weak"
	weak.CreatedAt, weak.UpdatedAt = domain.NowNano(), domain.NowNano()
	weak.ProductMatches = []*domain.ProductMatch{{BrandID: "brand-1", ProductID: "p1", ProductFitScore: 0, ProductFitBand: domain.ProductFitBandWeak, Reasons: []domain.ProductFitReason{{Dimension: domain.ProductFitPain, Score: 0, Reason: "無痛點證據"}, {Dimension: domain.ProductFitScenario, Score: 0, Reason: "無情境證據"}, {Dimension: domain.ProductFitAudience, Score: 0, Reason: "無受眾證據"}, {Dimension: domain.ProductFitCapability, Score: 0, Reason: "無能力證據"}}}}
	if _, err := svc.Repo.UpsertByExternalID(ctx, weak); err != nil {
		t.Fatal(err)
	}
	strong := integrationOpportunity(42)
	strong.ID, strong.ExternalID = "strong", "strong"
	strong.CreatedAt, strong.UpdatedAt = domain.NowNano(), domain.NowNano()
	strong.ProductMatches = []*domain.ProductMatch{integrationMatch("p2", 80)}
	if _, err := svc.Repo.UpsertByExternalID(ctx, strong); err != nil {
		t.Fatal(err)
	}
	all, err := svc.GetTodayFiltered(ctx, 42, domain.OpportunityListFilter{})
	if err != nil {
		t.Fatal(err)
	}
	if all.Stats.Total != 1 || all.EmptyReason != "" {
		t.Fatalf("weak product leaked into today: %+v", all)
	}
	selected, err := svc.GetTodayFiltered(ctx, 42, domain.OpportunityListFilter{ProductID: "p2", FitBand: domain.ProductFitBandStrong})
	if err != nil {
		t.Fatal(err)
	}
	selectedID := ""
	for _, card := range append(append(selected.High, selected.Mid...), selected.Low...) {
		selectedID = card.Opportunity.ExternalID
	}
	if selected.Stats.Total != 1 || selectedID != "strong" {
		t.Fatalf("selected product filter: %+v", selected)
	}
	noMatch, err := svc.GetTodayFiltered(ctx, 42, domain.OpportunityListFilter{ProductID: "missing"})
	if err != nil {
		t.Fatal(err)
	}
	if noMatch.EmptyReason != "no_eligible_product_match" {
		t.Fatalf("empty selected reason=%q", noMatch.EmptyReason)
	}
}
