package usecase

import (
	"context"
	"sync"
	"testing"

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

func TestOpportunityInboxConcurrentUpsertKeepsOneIdentity(t *testing.T) {
	repo := repository.NewMemory()
	const workers = 20
	var wg sync.WaitGroup
	for i := 0; i < workers; i++ {
		wg.Add(1)
		go func(i int) {
			defer wg.Done()
			_, _ = repo.UpsertByExternalID(context.Background(), &domain.Opportunity{
				OwnerUID: 42, ExternalID: "https://threads.net/@a/post/1", Permalink: "https://threads.net/@a/post/1",
				Text: "有人推薦保母嗎", Status: domain.OppQualified, IntentScore: 60,
				IntentBand: domain.BandMid, Reasons: validRaceReasons(), MatchedTerms: []string{"保母", string(rune('a' + i%3))},
			})
		}(i)
	}
	wg.Wait()
	list, total, err := repo.ListOpportunities(context.Background(), 42, domain.OpportunityListFilter{})
	if err != nil || total != 1 || len(list) != 1 {
		t.Fatalf("duplicate identity created: total=%d list=%d err=%v", total, len(list), err)
	}
}

func validRaceReasons() []domain.OpportunityReason {
	return []domain.OpportunityReason{
		{Dimension: domain.DimAuthenticity, Score: 30, Reason: "真實求助"},
		{Dimension: domain.DimIntent, Score: 30, Reason: "明確求推薦"},
		{Dimension: domain.DimRegion, Score: 15, Reason: "地區未知"},
		{Dimension: domain.DimFreshness, Score: 15, Reason: "近期"},
		{Dimension: domain.DimFit, Score: 10, Reason: "命中服務"},
	}
}
