package handlers

import (
	"context"
	"encoding/json"
	"errors"
	"net/http/httptest"
	"net/url"
	"strings"
	"sync/atomic"
	"testing"
	"time"

	"github.com/gin-gonic/gin"
	"go.mau.fi/whatsmeow/types"
	"gorm.io/gorm"
	"wa-assistant/backend/models"
	"wa-assistant/backend/services"
)

func notificationTestDB(t *testing.T) *gorm.DB {
	t.Helper()
	db := workflowTestDB(t)
	if err := db.AutoMigrate(&models.HandoffNotification{}); err != nil {
		t.Fatal(err)
	}
	if err := db.Model(&models.Agent{}).Where("id = 1").Updates(map[string]any{"handoff_notify_enabled": true, "handoff_notify_number": "6281234567890", "handoff_inbox_url": "https://chat.example.com/app", "number": "6281987654321"}).Error; err != nil {
		t.Fatal(err)
	}
	return db
}

func queuedNotification(t *testing.T, db *gorm.DB) models.HandoffNotification {
	t.Helper()
	created, err := ensureHandoffDetails(1, "6281111111111", "Mau dibantu cek permintaan saya", "needs_review")
	if err != nil || !created {
		t.Fatalf("queue handoff: %t %v", created, err)
	}
	var row models.HandoffNotification
	if err := db.First(&row).Error; err != nil {
		t.Fatal(err)
	}
	return row
}

func TestHandoffNotificationIsAtomicAndDeduplicated(t *testing.T) {
	db := notificationTestDB(t)
	row := queuedNotification(t, db)
	created, err := ensureHandoffDetails(1, "6281111111111", "Ada perkembangan?", "needs_review")
	if err != nil || created {
		t.Fatalf("repeat: %t %v", created, err)
	}
	var count int64
	db.Model(&models.HandoffNotification{}).Count(&count)
	if count != 1 || row.Status != "pending" || row.MessageID == "" {
		t.Fatalf("duplicate/missing job: %d %+v", count, row)
	}
	for _, want := range []string{"Pelanggan: +6281111111111", "Mau dibantu cek permintaan saya", "agent=1", "sender=6281111111111", "AI sedang dijeda"} {
		if !strings.Contains(row.Message, want) {
			t.Fatalf("notice missing %q", want)
		}
	}
	if !isInternalHandoffNotification(1, row.MessageID) || isInternalHandoffNotification(2, row.MessageID) {
		t.Fatal("internal notice lookup crosses agents")
	}
	OnWAOwnMessage(1, types.NewJID(row.Recipient, types.DefaultUserServer), services.IncomingMessage{WAMsgID: row.MessageID, Text: row.Message})
	db.Model(&models.ChatHistory{}).Count(&count)
	if count != 0 {
		t.Fatal("internal alert became a customer message")
	}
	var visible map[string]any
	encoded, _ := json.Marshal(row)
	_ = json.Unmarshal(encoded, &visible)
	for _, private := range []string{"message", "recipient", "message_id", "lock_token"} {
		if _, ok := visible[private]; ok {
			t.Fatalf("delivery status exposes %s", private)
		}
	}
}

func TestHandoffNotificationRetriesSameMessageAndStopsAfterSuccess(t *testing.T) {
	db := notificationTestDB(t)
	row := queuedNotification(t, db)
	now := time.Now().Add(time.Second)
	var ids []string
	send := func(_ context.Context, job models.HandoffNotification) error {
		ids = append(ids, job.MessageID)
		if len(ids) == 1 {
			return errors.New("fixture connection down")
		}
		// Another worker must not acquire the active lease while send is running.
		processHandoffNotifications(context.Background(), now.Add(time.Minute), func(context.Context, models.HandoffNotification) error {
			t.Fatal("parallel duplicate send")
			return nil
		})
		return nil
	}
	processHandoffNotifications(context.Background(), now, send)
	db.First(&row, row.ID)
	if row.Status != "pending" || row.Attempts != 1 || row.NextAttemptAt == nil {
		t.Fatalf("retry not durable: %+v", row)
	}
	processHandoffNotifications(context.Background(), now.Add(time.Second), send)
	if len(ids) != 1 {
		t.Fatal("retried before backoff")
	}
	processHandoffNotifications(context.Background(), now.Add(61*time.Second), send)
	db.First(&row, row.ID)
	if row.Status != "sent" || row.Attempts != 2 || row.SentAt == nil {
		t.Fatalf("delivery not recorded: %+v", row)
	}
	processHandoffNotifications(context.Background(), now.Add(time.Hour), send)
	if len(ids) != 2 || ids[0] != ids[1] {
		t.Fatal("message ID changed or successful job resent")
	}
}

func TestHandoffNotificationConcurrentWorkersSendOnce(t *testing.T) {
	db := notificationTestDB(t)
	queuedNotification(t, db)
	started, release, finished := make(chan struct{}, 2), make(chan struct{}), make(chan struct{})
	var sends atomic.Int32
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	send := func(ctx context.Context, _ models.HandoffNotification) error {
		sends.Add(1)
		started <- struct{}{}
		select {
		case <-release:
			return nil
		case <-ctx.Done():
			return ctx.Err()
		}
	}
	now := time.Now().Add(time.Second)
	go func() { defer close(finished); processHandoffNotifications(ctx, now, send) }()
	select {
	case <-started:
	case <-ctx.Done():
		close(release)
		<-finished
		t.Fatal("first worker did not claim the job")
	}
	processHandoffNotifications(ctx, now, send)
	close(release)
	<-finished
	if sends.Load() != 1 {
		t.Fatalf("concurrent workers sent %d messages", sends.Load())
	}
}

func TestHandoffNotificationCancelsWhenClaimedResumedOrDestinationChanges(t *testing.T) {
	for _, scenario := range []string{"claimed", "resumed", "disabled", "destination_changed", "linked_destination"} {
		t.Run(scenario, func(t *testing.T) {
			db := notificationTestDB(t)
			row := queuedNotification(t, db)
			switch scenario {
			case "claimed":
				db.Model(&models.Handoff{}).Where("id = ?", row.HandoffID).Update("status", "handling")
			case "resumed":
				db.Delete(&models.Handoff{}, row.HandoffID)
			case "disabled":
				db.Model(&models.Agent{}).Where("id = 1").Update("handoff_notify_enabled", false)
			case "destination_changed":
				db.Model(&models.Agent{}).Where("id = 1").Update("handoff_notify_number", "6281222222222")
			case "linked_destination":
				db.Create(&models.Agent{ID: 2, TenantID: 2, Number: row.Recipient})
			}
			processHandoffNotifications(context.Background(), time.Now().Add(time.Second), func(context.Context, models.HandoffNotification) error {
				t.Fatal("stale/internal handoff sent")
				return nil
			})
			db.First(&row, row.ID)
			if scenario != "linked_destination" && row.Status != "cancelled" {
				t.Fatalf("job not cancelled: %s", row.Status)
			}
		})
	}
}

func TestHandoffNotificationRecoversLeaseAndLimitsFailures(t *testing.T) {
	db := notificationTestDB(t)
	row := queuedNotification(t, db)
	past := time.Now().Add(-time.Minute)
	db.Model(&row).Updates(map[string]any{"status": "sending", "locked_until": past, "lock_token": "old-worker"})
	sends := 0
	send := func(_ context.Context, job models.HandoffNotification) error {
		sends++
		if job.MessageID != row.MessageID {
			t.Fatal("recovery changed message ID")
		}
		return errors.New("offline")
	}
	for i := 0; i < 8; i++ {
		processHandoffNotifications(context.Background(), time.Now().Add(time.Duration(i)*time.Hour), send)
	}
	db.First(&row, row.ID)
	if sends != maxHandoffNotificationAttempts || row.Status != "failed" {
		t.Fatalf("unbounded retries: %d %s", sends, row.Status)
	}
}

func TestHandoffNotificationSettingsValidationAndScope(t *testing.T) {
	db := notificationTestDB(t)
	params := gin.Params{{Key: "id", Value: "1"}}
	valid := handoffNotificationSettings{Enabled: true, Number: "+62 812-3456-7890", DashboardURL: "https://chat.example.com"}
	w := workflowRequest(t, SaveHandoffNotificationSettings, valid, params)
	if w.Code != 200 {
		t.Fatalf("save: %s", w.Body.String())
	}
	var agent models.Agent
	db.First(&agent, 1)
	if agent.HandoffNotifyNumber != "6281234567890" || agent.HandoffInboxURL != "https://chat.example.com/app" {
		t.Fatal("settings normalization failed")
	}
	for _, number := range []string{"", "628123@g.us", "6281987654321", "abc6281234567"} {
		req := valid
		req.Number = number
		if got := workflowRequest(t, SaveHandoffNotificationSettings, req, params); got.Code != 400 {
			t.Fatalf("invalid number %q accepted: %d", number, got.Code)
		}
	}
	for _, address := range []string{"javascript:alert(1)", "http://localhost:8181/app", "https://user:pass@example.com", "https://example.com/app?token=secret"} {
		req := valid
		req.DashboardURL = address
		if got := workflowRequest(t, SaveHandoffNotificationSettings, req, params); got.Code != 400 {
			t.Fatalf("invalid URL accepted: %d", got.Code)
		}
	}
	db.Create(&models.Agent{ID: 2, TenantID: 2})
	if got := workflowRequest(t, SaveHandoffNotificationSettings, valid, gin.Params{{Key: "id", Value: "2"}}); got.Code != 404 {
		t.Fatal("cross-tenant settings accepted")
	}
	router := gin.New()
	router.Use(func(c *gin.Context) { c.Set("tenant_id", uint(1)); c.Set("role", "cs"); c.Next() })
	router.PUT("/agents/:id/handoff-notifications", RequireTenantAdmin(), SaveHandoffNotificationSettings)
	r := httptest.NewRecorder()
	router.ServeHTTP(r, httptest.NewRequest("PUT", "/agents/1/handoff-notifications", strings.NewReader(`{}`)))
	if r.Code != 403 {
		t.Fatalf("CS can change notification destination: %d", r.Code)
	}
	u, _ := url.Parse(handoffInboxLink(agent.HandoffInboxURL, 1, "6281111111111"))
	if u.Query().Get("sender") != "6281111111111" || u.Query().Get("agent") != "1" || u.Query().Get("tab") != "inbox" {
		t.Fatal("Inbox link lost scope")
	}
}

func TestChangingNotificationSettingsCancelsQueuedDataWithoutSending(t *testing.T) {
	db := notificationTestDB(t)
	row := queuedNotification(t, db)
	w := workflowRequest(t, SaveHandoffNotificationSettings, handoffNotificationSettings{Enabled: true, Number: "6281222222222"}, gin.Params{{Key: "id", Value: "1"}})
	if w.Code != 200 {
		t.Fatalf("save: %s", w.Body.String())
	}
	db.First(&row, row.ID)
	if row.Status != "cancelled" || row.Recipient != "6281234567890" {
		t.Fatal("old customer data rerouted to new destination")
	}
}

func TestAssignedCSCanClaimThroughRouteGuardButCannotChangeNotifications(t *testing.T) {
	db := notificationTestDB(t)
	tid := uint(1)
	db.Create(&models.User{ID: 7, TenantID: &tid, Username: "fixture-cs", Role: "cs", Active: true})
	row := queuedNotification(t, db)
	db.Create(&models.UserAgentAssignment{TenantID: 1, AgentID: 1, UserID: 7})
	router := gin.New()
	router.Use(func(c *gin.Context) {
		c.Set("tenant_id", uint(1))
		c.Set("user_id", uint(7))
		c.Set("role", "cs")
		c.Next()
	}, CSRouteGuard())
	router.POST("/api/agents/:id/handoffs/:sender/claim", ClaimHandoff)
	router.PUT("/api/agents/:id/handoff-notifications", RequireTenantAdmin(), SaveHandoffNotificationSettings)
	w := httptest.NewRecorder()
	router.ServeHTTP(w, httptest.NewRequest("POST", "/api/agents/1/handoffs/6281111111111/claim", nil))
	if w.Code != 200 {
		t.Fatalf("assigned CS cannot claim: %d %s", w.Code, w.Body.String())
	}
	var ho models.Handoff
	db.First(&ho, row.HandoffID)
	if ho.Status != "handling" || ho.AssignedUserID != 7 {
		t.Fatal("claim did not record the owner")
	}
	w = httptest.NewRecorder()
	router.ServeHTTP(w, httptest.NewRequest("PUT", "/api/agents/1/handoff-notifications", strings.NewReader(`{}`)))
	if w.Code != 403 {
		t.Fatal("CS can change notification settings")
	}
	db.Where("user_id = 7").Delete(&models.UserAgentAssignment{})
	w = httptest.NewRecorder()
	router.ServeHTTP(w, httptest.NewRequest("POST", "/api/agents/1/handoffs/6281111111111/claim", nil))
	if w.Code != 404 {
		t.Fatal("unassigned CS can claim")
	}
}

func TestSimulatedServiceHandoffDoesNotNotifyRealCS(t *testing.T) {
	db, form, _ := serviceTestDB(t)
	db.AutoMigrate(&models.HandoffNotification{})
	db.Model(&models.Agent{}).Where("id = 1").Updates(map[string]any{"handoff_notify_enabled": true, "handoff_notify_number": "6281234567890"})
	var agent models.Agent
	db.First(&agent, 1)
	state := &aiFormSimulation{FormID: form.ID, Status: "confirming", Data: map[string]string{"name": "edi", "quantity": "2", "schedule": "besok"}}
	result, _ := simulateAIForm(context.Background(), agent, state, "konfirmasi", false)
	if !result.handoff {
		t.Fatal("simulation did not reach handoff")
	}
	for _, model := range []any{&models.HandoffNotification{}, &models.Handoff{}, &models.AIFormSubmission{}} {
		var count int64
		db.Model(model).Count(&count)
		if count != 0 {
			t.Fatalf("simulation created real work: %T", model)
		}
	}
}
