package services

import (
	"context"
	"strings"
	"testing"
	"wa-assistant/backend/models"

	"github.com/cloudwego/eino/components/tool"
)

func TestAgentCalculationRequiresRealPriceAndCustomerQuantity(t *testing.T) {
	db := agenticTestDB(t)
	db.AutoMigrate(&models.Product{})
	p := models.Product{AgentID: 1, TenantID: 1, Name: "Kaos Nusa", Price: "Rp75.000"}
	db.Create(&p)
	s := &agentTurnState{productFacts: map[uint]models.Product{p.ID: p}, userMessage: "Kalau beli 2 pcs total berapa?"}
	good := calculationInput{ProductID: p.ID, Quantity: 2, UnitPrice: 75000}
	out, issue := s.calculateTotal(context.Background(), 1, good)
	if issue != "" || out.Subtotal != 150000 {
		t.Fatalf("wrong subtotal: %+v %s", out, issue)
	}
	good.UnitPrice = 99000
	if _, issue := s.calculateTotal(context.Background(), 1, good); issue == "" {
		t.Fatal("invented unit price accepted")
	}
	good.UnitPrice = 75000
	good.Quantity = 3
	if _, issue := s.calculateTotal(context.Background(), 1, good); issue == "" {
		t.Fatal("invented quantity accepted")
	}
	if !strings.Contains(s.businessEvidence, "150000") {
		t.Fatal("calculation unavailable for answer check")
	}
	s.clearCalculations()
	if strings.Contains(s.businessEvidence, "150000") {
		t.Fatal("old total survived refreshed sources")
	}
}

func TestCalculationUnderstandsCustomerCountWithConversationReference(t *testing.T) {
	for _, text := range []string{"Kalau saya ambil dua yang tadi, subtotalnya berapa?", "Saya pesan dua puluh tiga", "Berapa untuk 23 unit?"} {
		quantity := int64(23)
		if strings.Contains(text, "yang tadi") {
			quantity = 2
		}
		state := &agentTurnState{userMessage: text, customerMessages: []string{"Beli 5 unit berapa?"}}
		if !state.hasCustomerQuantity(quantity) || state.hasCustomerQuantity(5) {
			t.Fatalf("latest customer count was not respected: %s", text)
		}
	}
}

func TestCalculatedTotalSurvivesLookupUntilItsPriceChanges(t *testing.T) {
	db := agenticTestDB(t)
	if err := db.AutoMigrate(&models.Product{}, &models.AppSetting{}); err != nil {
		t.Fatal(err)
	}
	product := models.Product{AgentID: 1, TenantID: 1, Name: "Tas Rimba", Price: "Rp149.000"}
	db.Create(&product)
	state := &agentTurnState{userMessage: "Kalau saya ambil dua yang tadi, subtotalnya berapa?"}
	all, err := makeAgentTools(1, ChatOptions{DryRun: true}, state)
	if err != nil {
		t.Fatal(err)
	}
	var lookup tool.InvokableTool
	for _, candidate := range all {
		info, _ := candidate.Info(context.Background())
		if info.Name == "lookup_products" {
			lookup = candidate.(tool.InvokableTool)
		}
	}
	if lookup == nil {
		t.Fatal("lookup tool missing")
	}
	if _, err := lookup.InvokableRun(context.Background(), `{"query":"Tas Rimba"}`); err != nil {
		t.Fatal(err)
	}
	if total, issue := state.calculateTotal(context.Background(), 1, calculationInput{ProductID: product.ID, Quantity: 2, UnitPrice: 149000}); issue != "" || total.Subtotal != 298000 {
		t.Fatalf("calculation failed: %+v %s", total, issue)
	}
	lookup.InvokableRun(context.Background(), `{"query":"Tas Rimba"}`)
	if !strings.Contains(state.businessEvidence, "298000") {
		t.Fatal("unchanged lookup lost a valid calculation")
	}
	db.Model(&product).UpdateColumn("price", "Rp159.000")
	lookup.InvokableRun(context.Background(), `{"query":"Tas Rimba"}`)
	if strings.Contains(state.businessEvidence, "298000") {
		t.Fatal("stale total survived an actual price change")
	}
}

func TestCalculationBindsNaturalCountsToCatalogProducts(t *testing.T) {
	products := map[uint]models.Product{
		1: {ID: 1, Name: "Tas Rimba"},
		2: {ID: 2, Name: "Tumbler Langit"},
	}
	for _, tc := range []struct {
		message string
		product uint
		count   int64
		allowed bool
	}{
		{"Berapa subtotal dua Tas Rimba?", 1, 2, true},
		{"Berapa subtotal Tas Rimba 2?", 1, 2, true},
		{"Dua Tas Rimba dan tiga Tumbler Langit berapa?", 1, 2, true},
		{"Dua Tas Rimba dan tiga Tumbler Langit berapa?", 2, 3, true},
		{"Dua Tas Rimba dan tiga Tumbler Langit berapa?", 1, 3, false},
		{"Dua Tas Rimba dan tiga Tumbler Langit berapa?", 0, 2, false},
		{"Berapa dua Tumbler Langit?", 1, 2, false},
		{"Dua Tas Rimba, eh tiga Tas Rimba saja", 1, 2, false},
		{"Dua Tas Rimba, eh tiga Tas Rimba saja", 1, 3, true},
		{"Ganti jadi tiga", 1, 2, false},
		{"Ganti jadi tiga", 1, 3, true},
		{"Tas Rimba Rp149.000", 1, 149, false},
	} {
		state := &agentTurnState{productFacts: products, userMessage: tc.message, customerMessages: []string{"Saya beli dua Tas Rimba"}}
		if got := state.hasCustomerProductQuantity(tc.count, tc.product); got != tc.allowed {
			t.Errorf("message=%q product=%d count=%d got=%t", tc.message, tc.product, tc.count, got)
		}
	}
}
