package usecase

import (
	"context"
	"testing"

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

func TestCandidateEvaluatorSkipsOwnerHistoricalCanonicalIdentity(t *testing.T) {
	store := repository.NewMemory()
	if err := store.MarkSeenIdentity(context.Background(), 7, "threads-post:SameCode", "old-post", 1); err != nil {
		t.Fatal(err)
	}
	evaluator := NewCandidateEvaluator(&domain.RunBrief{
		Mode: domain.ModeActivity, Intent: "咖啡店", ScanTerms: []string{"咖啡店"},
	})
	evaluator.SetHistoricalSeenLookup(func(identity string) (bool, error) {
		return store.HasSeenIdentity(context.Background(), 7, identity)
	})
	got := evaluator.Evaluate(ThreadSearchResult{
		URL: "https://www.threads.com/@renamed/post/SameCode?share=1", Snippet: "分享最近找到的咖啡店",
	})
	if got.Decision != CandidateDuplicate || got.Reason == "" {
		t.Fatalf("historical alias evaluation=%+v", got)
	}
	if stats := evaluator.Stats(); stats.Duplicate != 1 || stats.Eligible != 0 {
		t.Fatalf("historical stats=%+v", stats)
	}
}

func TestCandidateEvaluatorDoesNotShareHistoryAcrossOwners(t *testing.T) {
	store := repository.NewMemory()
	if err := store.MarkSeenIdentity(context.Background(), 7, "threads-post:SameCode", "old-post", 1); err != nil {
		t.Fatal(err)
	}
	evaluator := NewCandidateEvaluator(&domain.RunBrief{
		Mode: domain.ModeActivity, Intent: "咖啡店", ScanTerms: []string{"咖啡店"},
	})
	evaluator.SetHistoricalSeenLookup(func(identity string) (bool, error) {
		return store.HasSeenIdentity(context.Background(), 8, identity)
	})
	got := evaluator.Evaluate(ThreadSearchResult{
		URL: "https://www.threads.net/@alice/post/SameCode", Snippet: "分享最近找到的咖啡店",
	})
	if got.Decision != CandidateEligible {
		t.Fatalf("cross-owner history leaked: %+v", got)
	}
}
