package usecase

import (
	"context"
	"testing"
	"time"

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

func TestProductFitStaleCandidateStillPersistsCompleteMatch(t *testing.T) {
	svc, watch, cand := productJudgeFixture("")
	cand.PostedAt = time.Now().Add(-20 * 24 * time.Hour).UnixNano()
	result, _, err := svc.JudgeCandidate(context.Background(), 42, nil, watch, cand)
	if err != nil {
		t.Fatal(err)
	}
	if result.Status == domain.OppRejected {
		t.Fatalf("a 20-day-old demand post must stay judgeable, got rejected: %+v", result)
	}
	if result.ProductMatch == nil || len(result.ProductMatch.Reasons) != 4 {
		t.Fatalf("stale candidate lost product evidence: %+v", result)
	}
	if result.ProductMatch.ProductFitScore == 0 {
		t.Fatalf("stale candidate should retain fit evidence: %+v", result.ProductMatch)
	}
}

func TestProductMatchSnapshotRemainsStaleAfterProductUpdate(t *testing.T) {
	ctx := context.Background()
	mem := repository.NewMemory()
	op, err := mem.UpsertByExternalID(ctx, integrationOpportunity(1))
	if err != nil {
		t.Fatal(err)
	}
	old := integrationMatch("p1", 60)
	old.ProductLabelSnapshot, old.ProductUpdatedAt = "舊產品", 10
	if _, err := mem.MergeProductMatch(ctx, 1, op.ID, old); err != nil {
		t.Fatal(err)
	}
	updated := integrationMatch("p1", 100)
	updated.ProductLabelSnapshot, updated.ProductUpdatedAt = "新版產品", 20
	if _, err := mem.MergeProductMatch(ctx, 1, op.ID, updated); err != nil {
		t.Fatal(err)
	}
	got, err := mem.GetOpportunity(ctx, op.ID)
	if err != nil {
		t.Fatal(err)
	}
	if got.ProductMatches[0].ProductLabelSnapshot != "舊產品" || got.ProductMatches[0].ProductUpdatedAt != 10 || got.ProductMatches[0].ProductFitScore != 60 {
		t.Fatalf("old product match was rewritten: %+v", got.ProductMatches[0])
	}
}
