package services

import (
	"context"
	"testing"
	"time"
	"wa-assistant/backend/models"
)

func TestKnowledgeProductAspectOutranksRepeatedLongName(t *testing.T) {
	embMu.Lock()
	oldEnabled := embEnabled
	embEnabled = false
	embMu.Unlock()
	t.Cleanup(func() { embMu.Lock(); embEnabled = oldEnabled; embMu.Unlock() })
	firstURL := "https://store.example/p/source-code-wa-blast-plus-ai-assistant"
	secondURL := "https://store.example/p/masterclass-laravel-12-belajar-laravel-dari-dasar-sampai-mahir"
	items := []KBItem{
		{K: models.Knowledge{ID: 1, Source: "web", SourceURL: firstURL, Question: "Berapa harga produk ini?", Answer: "Harganya Rp199.000."}},
		{K: models.Knowledge{ID: 2, Source: "web", SourceURL: firstURL, Question: "Apa saja yang saya dapatkan setelah membeli?", Answer: "Source code dan panduan instalasi."}},
		{K: models.Knowledge{ID: 3, Source: "web", SourceURL: firstURL, Question: "Apa itu Source Code WA Blast plus AI Assistant?", Answer: "Sistem untuk mengirim pesan.", CreatedAt: time.Now()}},
		{K: models.Knowledge{ID: 4, Source: "web", SourceURL: secondURL, Question: "Apa saja yang saya dapatkan setelah membeli?", Answer: "Source code, sertifikat dan konsultasi."}},
		{K: models.Knowledge{ID: 5, Source: "web", SourceURL: secondURL, Question: "Berapa harga Masterclass Laravel 12?", Answer: "Harganya Rp179.000."}},
	}
	for _, tc := range []struct {
		query     string
		first     uint
		forbidden uint
	}{
		{"Harga source code WA Blast plus AI Assistant berapa sekarang?", 1, 5},
		{"Apa saja yang didapat setelah membeli Source Code WA Blast plus AI Assistant?", 2, 4},
		{"Apa saja yang didapat setelah membeli Masterclass Laravel 12?", 4, 2},
	} {
		t.Run(tc.query, func(t *testing.T) {
			got, _, _ := selectKnowledgeWithLimit(context.Background(), tc.query, items, 5)
			if len(got) == 0 || got[0].ID != tc.first {
				t.Fatalf("specific aspect lost to product name: %+v", got)
			}
			for _, k := range got {
				if k.ID == tc.forbidden {
					t.Fatalf("other product leaked: %+v", got)
				}
			}
		})
	}
	got, _, _ := selectKnowledgeWithLimit(context.Background(), "Bandingkan harga kelas Laravel 12 dan Source Code WA Blast plus AI Assistant. Buat satu poin per produk.", items, 5)
	found := map[uint]bool{}
	for _, k := range got {
		found[k.ID] = true
	}
	if !found[1] || !found[5] {
		t.Fatalf("comparison dropped one product: %+v", got)
	}
}

func TestKnowledgeProductComparisonIgnoresUnrelatedAgentAndDraft(t *testing.T) {
	db := agenticTestDB(t)
	url := "https://store.example/p/source-code-paket-toko"
	rows := []models.Knowledge{
		{ID: 1, AgentID: 1, SourceURL: url, Question: "Apakah Paket Toko boleh dipakai untuk klien?", Answer: "Paket Toko boleh dipakai untuk klien.", Scope: "general", ReviewStatus: "published", Active: true},
		{ID: 2, AgentID: 1, SourceURL: url, Question: "Batasan lisensi Paket Toko?", Answer: "Paket Toko hanya untuk internal, dilarang untuk klien.", Scope: "general", ReviewStatus: "published", Active: true},
		{ID: 3, AgentID: 2, SourceURL: url, Question: "Rahasia akun lain", Answer: "RAHASIA", Scope: "general", ReviewStatus: "published", Active: true},
		{ID: 4, AgentID: 1, SourceURL: url, Question: "Usulan", Answer: "BELUM DISETUJUI", Scope: "general", ReviewStatus: "draft", Active: true},
	}
	if err := db.Create(&rows).Error; err != nil {
		t.Fatal(err)
	}
	InvalidateKB(1)
	q := "Apakah Paket Toko boleh dipakai untuk klien?"
	s := &agentTurnState{userMessage: q, knowledge: rows[:1], policy: responsePolicyForLength(selectAIResponsePolicy(q, "", "", 1), "balanced", q)}
	s.reviewAnswer = func(ctx context.Context, _, _, _ string) (answerEvidenceReview, error) {
		data, ok := ctx.Value(answerComparisonKey{}).([]map[string]any)
		if !ok || len(data) != 1 || data[0]["source_id"] != uint(2) {
			t.Fatalf("comparison must find unselected live same-product restriction only: %+v", data)
		}
		return answerEvidenceReview{ConflictingSources: true}, nil
	}
	result := s.checkAnswer(context.Background(), 1, answerCheckInput{Answer: rows[0].Answer, Kind: "answer", SourceIDs: []uint{1}})
	if result.Approved || result.Issue != "knowledge_conflict" || s.handoffReason != "knowledge_conflict" {
		t.Fatalf("conflict not handed off: %+v", result)
	}
}

func TestPublishedCorrectionInheritsProductWithoutRevivingParentFacts(t *testing.T) {
	db := agenticTestDB(t)
	rows := []models.Knowledge{
		{ID: 10, AgentID: 1, SourceURL: "https://store.example/p/source-code-wa-blast", Question: "Berapa harga produk ini?", Answer: "Harga lama Rp75.000.", ReviewStatus: "archived"},
		{ID: 11, AgentID: 1, SourceURL: "simulation://fixture", Source: "correction", SupersedesID: 10, Question: "Berapa harga produk ini?", Answer: "Harga Rp99.000.", ReviewStatus: "published", Active: true},
		{ID: 20, AgentID: 1, SourceURL: "https://store.example/p/masterclass-laravel-12", Question: "Berapa harga produk ini?", Answer: "Harga Rp179.000.", ReviewStatus: "published", Active: true},
		{ID: 30, AgentID: 2, SourceURL: "https://private.example/p/secret-other-agent", Question: "Rahasia", ReviewStatus: "archived"},
		{ID: 31, AgentID: 1, SourceURL: "simulation://invalid-link", SupersedesID: 30, Question: "Catatan tanpa produk", ReviewStatus: "draft"},
	}
	if err := db.Create(&rows).Error; err != nil {
		t.Fatal(err)
	}
	InvalidateKB(1)
	items, err := LoadKnowledgeForContext(context.Background(), 1)
	if err != nil {
		t.Fatal(err)
	}
	if len(items) != 2 {
		t.Fatalf("parent/draft/foreign facts returned: %+v", items)
	}
	var correction models.Knowledge
	for _, item := range items {
		if item.K.ID == 11 {
			correction = item.K
		}
	}
	if id, _ := knowledgeSubject(correction); id != rows[0].SourceURL || correction.SourceURL != "simulation://fixture" {
		t.Fatalf("correction lost product/provenance: %+v", correction)
	}
	if _, issue := currentKnowledgeSources(context.Background(), 1, []models.Knowledge{correction}); issue != "" {
		t.Fatal(issue)
	}
	for _, tc := range []struct {
		q             string
		want, exclude uint
	}{{"harga WA Blast", 11, 20}, {"harga Laravel 12", 20, 11}} {
		got, _, _ := selectKnowledgeWithLimit(context.Background(), tc.q, items, 5)
		if len(got) == 0 || got[0].ID != tc.want {
			t.Fatalf("wrong correction scope: %s %+v", tc.q, got)
		}
		for _, row := range got {
			if row.ID == tc.exclude {
				t.Fatal("correction crossed product")
			}
		}
	}
	if err := ResolveKnowledgeSubjects(db, 1, rows[4:]); err != nil {
		t.Fatal(err)
	}
	if rows[4].SubjectURL != "" {
		t.Fatal("foreign lineage leaked product metadata")
	}
}
