package services

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

func TestServiceCalculationUsesCustomerParticipants(t *testing.T) {
	for _, tc := range []struct {
		message string
		count   int64
		allowed bool
	}{
		{"Untuk 2 orang dewasa, total berapa?", 2, true},
		{"Untuk Reguler Double 2 orang dewasa, tolong hitungkan total harga, total DP, sisa pelunasan, dan tanggal terakhir pelunasan.", 2, true},
		{"Kembali ke umroh Reguler Double tanggal 10 November untuk 2 dewasa. Tolong cek harga terbaru sekarang, total berdua, DP, dan sisa pelunasannya sebelum saya lanjut.", 2, true},
		{"Saya ingin daftar dua peserta.", 2, true},
		{"Berapa untuk tiga jamaah?", 3, true},
		{"Jadi 3 jemaah dewasa.", 3, true},
		{"Untuk 2 dewasa dan 1 anak usia 4 tahun.", 2, true},
		{"Untuk 2 dewasa dan 1 anak usia 4 tahun.", 1, false},
		{"Untuk 2 dewasa dan 1 anak usia 4 tahun.", 4, false},
		{"Kami 2 orang dewasa, kamar quad berkapasitas 4 orang per kamar.", 2, true},
		{"Kami 2 orang dewasa, kamar quad berkapasitas 4 orang per kamar.", 4, false},
		{"Tanggal 10 November, selama 9 hari, anak usia 4 tahun.", 4, false},
		{"Tanggal 10 November, selama 9 hari, anak usia 4 tahun.", 9, false},
		{"Bukan 2, ganti jadi 3 peserta.", 2, false},
		{"Bukan 2, ganti jadi 3 peserta.", 3, true},
	} {
		t.Run(fmt.Sprintf("%s/%d", tc.message, tc.count), func(t *testing.T) {
			s := &agentTurnState{userMessage: tc.message, productFacts: map[uint]models.Product{1: {ID: 1, Name: "Paket perjalanan", Price: "Rp31.500.000 per jamaah dewasa"}}}
			if got := s.hasCustomerProductQuantity(tc.count, 1); got != tc.allowed {
				t.Fatalf("count=%d got=%t want=%t", tc.count, got, tc.allowed)
			}
		})
	}
}

func TestServiceDepositCalculationRequiresFreshPublishedTerms(t *testing.T) {
	db := agenticTestDB(t)
	if err := db.AutoMigrate(&models.Product{}); err != nil {
		t.Fatal(err)
	}
	p := models.Product{AgentID: 1, TenantID: 1, Name: "Perjalanan Double", Price: "Rp31.500.000 per jamaah dewasa"}
	k := models.Knowledge{AgentID: 1, Question: "DP perjalanan", Answer: "DP Rp5.000.000 per jamaah dewasa. Sisa adalah harga paket dikurangi DP. Booking dan penerimaan pembayaran harus dikonfirmasi tim.", Active: true, ReviewStatus: "published"}
	if err := db.Create(&p).Error; err != nil {
		t.Fatal(err)
	}
	if err := db.Create(&k).Error; err != nil {
		t.Fatal(err)
	}
	state := func() *agentTurnState {
		return &agentTurnState{userMessage: "Untuk 2 orang dewasa, berapa total, DP, dan sisa pelunasan?", productFacts: map[uint]models.Product{p.ID: p}, knowledge: []models.Knowledge{k}}
	}
	input := calculationInput{ProductID: p.ID, Quantity: 2, UnitPrice: 31500000, Subtract: &calculationDeductionInput{SourceID: k.ID, UnitPrice: 5000000}}
	s := state()
	out, issue := s.calculateTotal(context.Background(), 1, input)
	if issue != "" || out.Subtotal != 63000000 || out.DeductionSubtotal == nil || *out.DeductionSubtotal != 10000000 || out.Remainder == nil || *out.Remainder != 53000000 {
		t.Fatalf("result=%+v issue=%s", out, issue)
	}
	if !strings.Contains(s.businessEvidence, "53000000") || len(s.calculationSourceIDs) != 1 || s.calculationSourceIDs[0] != k.ID {
		t.Fatal("derived balance lost source provenance")
	}
	for _, invalid := range []calculationDeductionInput{{SourceID: k.ID, UnitPrice: 4000000}, {SourceID: k.ID, UnitPrice: 32000000}, {SourceID: k.ID + 999, UnitPrice: 5000000}, {SourceID: k.ID, UnitPrice: -1}} {
		input.Subtract = &invalid
		bad := state()
		if _, issue := bad.calculateTotal(context.Background(), 1, input); issue == "" || strings.Contains(bad.businessEvidence, "remainder") {
			t.Fatalf("invalid deduction accepted: %+v", invalid)
		}
	}
	if err := db.Model(&k).UpdateColumns(map[string]any{"active": false, "review_status": "archived"}).Error; err != nil {
		t.Fatal(err)
	}
	if issue := s.freshBusinessFacts(context.Background(), 1); issue == "" {
		t.Fatal("archived DP terms left balance usable")
	}
	s.clearCalculations()
	if strings.Contains(s.businessEvidence, "53000000") {
		t.Fatal("invalidated calculation remained evidence")
	}
}

func TestTravelSubtotalDoesNotRequireAnItemWord(t *testing.T) {
	db := agenticTestDB(t)
	if err := db.AutoMigrate(&models.Product{}); err != nil {
		t.Fatal(err)
	}
	p := models.Product{AgentID: 1, TenantID: 1, Name: "Paket perjalanan Double", Price: "Rp31.500.000 per jamaah dewasa"}
	db.Create(&p)
	s := &agentTurnState{userMessage: "Saya ingin berangkat untuk 2 orang dewasa", productFacts: map[uint]models.Product{p.ID: p}}
	total, issue := s.calculateTotal(context.Background(), 1, calculationInput{ProductID: p.ID, UnitPrice: 31500000, Quantity: 2})
	if issue != "" || total.Subtotal != 63000000 {
		t.Fatalf("subtotal=%+v issue=%s", total, issue)
	}
}
