package usecase

import (
	"context"
	"errors"
	"testing"

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

func TestEnrichDemandMapAddsAIOriginAndAdvancesVersion(t *testing.T) {
	repo := repository.NewMemory()
	svc := New(repo)
	svc.ProductSource = demandMapProducts{product: &ProductCatalogProduct{ID: "p1", OwnerUID: 42, Label: "服務", ProductContext: "換季", PainPoints: []string{"泛紅"}, ProviderCapabilityTerms: []string{"修護"}, UpdatedAt: 1}}
	// completeAI uses the injected client after resolving the test key.
	svc.AI = &enrichFakeAI{raw: `{"pain_phrases":[{"text":"皮膚刺癢","kind":"pain","basis_kind":"pain","basis_text":"泛紅","enabled":true}]}`}
	current, err := svc.GetDemandMap(context.Background(), 42, "p1")
	if err != nil {
		t.Fatal(err)
	}
	updated, err := svc.EnrichDemandMap(context.Background(), 42, "p1", "preview", current.MapVersion, 1)
	if err != nil {
		t.Fatal(err)
	}
	if updated.MapVersion != 2 || updated.AIEnrichedAt == 0 || updated.PainPhrases[len(updated.PainPhrases)-1].Origin != "ai" {
		t.Fatalf("unexpected enrichment: %+v", updated)
	}
}

func TestEnrichDemandMapRequiresCeiling(t *testing.T) {
	_, err := New(repository.NewMemory()).EnrichDemandMap(context.Background(), 42, "p1", "", 1, 0)
	if !errors.Is(err, domain.ErrValidation) {
		t.Fatalf("expected validation, got %v", err)
	}
}

type enrichFakeAI struct{ raw string }

func (f *enrichFakeAI) Complete(context.Context, string, string, string) (string, error) {
	return f.raw, nil
}
func (f *enrichFakeAI) CompleteStream(context.Context, string, string, string, func(string) error) (string, error) {
	return f.raw, nil
}
func (f *enrichFakeAI) ListModels(context.Context, string) ([]string, error) {
	return []string{"test"}, nil
}

var _ ai.Client = (*enrichFakeAI)(nil)
