package handlers

import (
	"encoding/json"
	"fmt"
	"strings"
	"sync"
	"testing"
	"time"

	"go.mau.fi/whatsmeow/types"
	"wa-assistant/backend/models"
)

func TestAdaptiveDebounceCompletenessAndBoundedPresence(t *testing.T) {
	for _, text := range []string{"halo", "kak", "p"} {
		if adaptiveDebounceDelay(text) != 5*time.Second {
			t.Fatal("short burst not protected", text)
		}
	}
	for _, text := range []string{"Bisa untuk hadiah?", "Iya datanya sudah benar", "Saya ingin menanyakan apakah paket ini mencakup layanan selama satu tahun."} {
		if adaptiveDebounceDelay(text) > 2*time.Second {
			t.Fatal("complete message delayed", text)
		}
	}
	now := time.Now()
	p := &pendingText{firstAt: now.Add(-2 * time.Second), dueAt: now.Add(-time.Second), composingUntil: now.Add(6 * time.Second)}
	if got := pendingTextDeadline(p, now); got != now.Add(3*time.Second) {
		t.Fatal("typing not extended", got)
	}
	p.composingUntil = time.Time{}
	if pendingTextDeadline(p, now).After(now) {
		t.Fatal("paused typing still waits")
	}
	// Paused removes the presence extension, not the short burst protection.
	// It must not flush immediately when the base debounce has not elapsed.
	p.dueAt = now.Add(time.Second)
	if got := pendingTextDeadline(p, now); got != p.dueAt {
		t.Fatal("paused event bypassed minimum burst window", got)
	}
	p.firstAt, p.composingUntil = now.Add(-maxDebounceWait), now.Add(time.Minute)
	if pendingTextDeadline(p, now).After(now) {
		t.Fatal("presence exceeds hard deadline")
	}
}

func TestAdaptiveDebouncePresenceIsScopedAndConcurrent(t *testing.T) {
	sender := types.NewJID("presence-fixture", types.DefaultUserServer)
	now := time.Now()
	first := &pendingText{firstAt: now, dueAt: now.Add(time.Minute)}
	other := &pendingText{firstAt: now, dueAt: now.Add(time.Minute)}
	debounceMu.Lock()
	pending[debounceKey(91, sender)], pending[debounceKey(92, sender)] = first, other
	debounceMu.Unlock()
	t.Cleanup(func() {
		debounceMu.Lock()
		defer debounceMu.Unlock()
		if first.timer != nil {
			first.timer.Stop()
		}
		if other.timer != nil {
			other.timer.Stop()
		}
		delete(pending, debounceKey(91, sender))
		delete(pending, debounceKey(92, sender))
	})
	var wg sync.WaitGroup
	for i := 0; i < 32; i++ {
		wg.Add(1)
		go func() { defer wg.Done(); updatePendingChatPresence(91, sender.User, true) }()
	}
	wg.Wait()
	debounceMu.Lock()
	valid := first.composingUntil.After(now) && other.composingUntil.IsZero()
	debounceMu.Unlock()
	if !valid {
		t.Fatal("typing leaked across agents or was lost")
	}
	updatePendingChatPresence(91, sender.User, false)
	debounceMu.Lock()
	paused := first.composingUntil.IsZero()
	debounceMu.Unlock()
	if !paused {
		t.Fatal("paused presence not applied")
	}
}

func TestCompletedCheckoutAcknowledgementIsScopedAndDoesNotCreateOrders(t *testing.T) {
	db, product, session := naturalCheckoutTestDB(t)
	order := models.ProductOrder{TenantID: session.TenantID, AgentID: session.AgentID, ProductID: product.ID, Sender: session.Sender, OrderCode: "ORD-REPEAT-TEST", Status: "confirmed"}
	if err := db.Create(&order).Error; err != nil {
		t.Fatal(err)
	}
	raw, _ := json.Marshal(map[string]string{confirmedOrderKey: fmt.Sprint(order.ID)})
	db.Model(&session).Updates(map[string]any{"status": "completed", "data_json": string(raw)})
	db.Create(&models.ChatHistory{AgentID: session.AgentID, Sender: session.Sender, Reply: "Pesanan " + order.OrderCode + " sudah dicatat.", DeliveryStatus: "sent", CreatedAt: time.Now()})
	for _, text := range []string{"Iya datanya sudah benar", "Oke kak", "benar, lanjut proses"} {
		started := time.Now()
		got := handleProductInteraction(session.AgentID, session.Sender, text, "")
		if !got.handled || !strings.Contains(got.reply, order.OrderCode) || got.aiContext != "" {
			t.Fatal("repeat went to AI", got)
		}
		t.Logf("repeat DB handler: %s", time.Since(started))
	}
	for _, text := range []string{"Belum benar", "Sudah benar?", "Oke tapi ubah alamat", "Oke saya mau pesan lagi", "Saya sudah transfer", "proses refund", "sudah sampai?"} {
		if got := handleProductInteraction(session.AgentID, session.Sender, text, ""); got.handled {
			t.Fatal("swallowed a new request", text)
		}
	}
	if got := completedOrderAcknowledgement(2, session.Sender, "iya benar", "", time.Now()); got.handled {
		t.Fatal("cross-agent order")
	}
	if got := completedOrderAcknowledgement(1, "another-contact", "iya benar", "", time.Now()); got.handled {
		t.Fatal("cross-contact order")
	}
	if got := completedOrderAcknowledgement(1, session.Sender, "", fmt.Sprintf("checkout:%d:confirm", session.ID), time.Now()); !got.handled {
		t.Fatal("repeat button unhandled")
	}
	if got := completedOrderAcknowledgement(1, session.Sender, "iya", "", time.Now().Add(16*time.Minute)); got.handled {
		t.Fatal("stale confirmation intercepted")
	}
	var count int64
	db.Model(&models.ProductOrder{}).Count(&count)
	if count != 1 {
		t.Fatal("duplicate order created", count)
	}
	db.Create(&models.ChatHistory{AgentID: session.AgentID, Sender: session.Sender, Reply: "Pilihan lainnya tersedia dalam warna biru.", DeliveryStatus: "sent", CreatedAt: time.Now().Add(time.Second)})
	if got := handleProductInteraction(session.AgentID, session.Sender, "oke kak", ""); got.handled {
		t.Fatal("acknowledgement of a different topic intercepted")
	}
}
