package handlers

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"strings"
	"sync"
	"sync/atomic"
	"testing"
	"time"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"wa-assistant/backend/models"
)

func reminderTestSetup(t *testing.T) (*gorm.DB, models.User, *gin.Engine) {
	db, user := csWorkspaceDB(t)
	if err := db.AutoMigrate(&models.ConversationWork{}, &models.FollowUpTask{}, &models.FollowUpReminderReceipt{}, &models.FollowUpNotificationSetting{}, &models.FollowUpNotificationDelivery{}); err != nil {
		t.Fatal(err)
	}
	r := gin.New()
	r.Use(AuthMiddleware(), CSRouteGuard())
	r.GET("/api/follow-up-reminders", ListFollowUpReminders)
	r.POST("/api/follow-up-reminders/claim", ClaimFollowUpReminders)
	r.POST("/api/follow-up-reminders/:taskID/snooze", SnoozeFollowUpReminder)
	r.GET("/api/agents/:id/follow-up-notifications", GetFollowUpNotificationSettings)
	r.PUT("/api/agents/:id/follow-up-notifications", SaveFollowUpNotificationSettings)
	return db, user, r
}
func reminderFixture(t *testing.T, db *gorm.DB, agentID uint, due time.Time, status string) models.FollowUpTask {
	t.Helper()
	k := fmt.Sprint(agentID, "-", due.UnixNano(), "-", status)
	// Match persisted/API times; SQL does not preserve monotonic clock readings.
	task := models.FollowUpTask{AgentID: agentID, Number: "6281234567890", Name: "Edi", Reason: "Konfirmasi pembelian", DueAt: due.Round(0), Status: status, Version: 1, SourceKey: k}
	if err := db.Create(&task).Error; err != nil {
		t.Fatal(err)
	}
	return task
}
func reminderIDs(t *testing.T, r *gin.Engine, user models.User, method, path string, body any) []followUpReminderItem {
	t.Helper()
	w := csRequest(r, user, method, path, body)
	if w.Code != 200 {
		t.Fatalf("%s %s: %d %s", method, path, w.Code, w.Body.String())
	}
	var res struct {
		Data []followUpReminderItem `json:"data"`
	}
	if err := json.Unmarshal(w.Body.Bytes(), &res); err != nil {
		t.Fatal(err)
	}
	return res.Data
}
func TestReminderQueueDueScopeOwnerAndRevocation(t *testing.T) {
	db, user, r := reminderTestSetup(t)
	now := time.Now()
	due := reminderFixture(t, db, 1, now.Add(-time.Minute), "pending")
	reminderFixture(t, db, 1, now.Add(time.Hour), "pending")
	reminderFixture(t, db, 1, now.Add(-2*time.Hour), "completed")
	reminderFixture(t, db, 1, now.Add(-3*time.Hour), "uncertain")
	reminderFixture(t, db, 2, now.Add(-time.Minute), "pending")
	reminderFixture(t, db, 3, now.Add(-time.Minute), "pending")
	items := reminderIDs(t, r, user, "GET", "/api/follow-up-reminders", nil)
	if len(items) != 1 || items[0].ID != due.ID {
		t.Fatalf("wrong due/scope count %d", len(items))
	}
	tid := uint(1)
	owner := models.User{ID: 8, Username: "budi", Name: "Budi", TenantID: &tid, Role: "cs", Active: true}
	db.Create(&owner)
	db.Create(&models.UserAgentAssignment{TenantID: 1, UserID: 8, AgentID: 1})
	work := models.ConversationWork{AgentID: 1, Sender: due.Number, Status: "open", AssignedUserID: 8}
	db.Create(&work)
	if got := reminderIDs(t, r, user, "GET", "/api/follow-up-reminders", nil); len(got) != 0 {
		t.Fatal("another owner's task leaked into personal queue")
	}
	if got := reminderIDs(t, r, owner, "GET", "/api/follow-up-reminders", nil); len(got) != 1 || got[0].AssignedName != "Budi" {
		t.Fatal("owner missing")
	}
	db.Where("user_id = ?", owner.ID).Delete(&models.UserAgentAssignment{})
	if got := reminderIDs(t, r, owner, "GET", "/api/follow-up-reminders", nil); len(got) != 0 {
		t.Fatal("revoked access remained")
	}
	if got := reminderIDs(t, r, user, "GET", "/api/follow-up-reminders", nil); len(got) != 1 {
		t.Fatal("invalid owner orphaned team reminder")
	}
}
func TestReminderAtomicClaimSnoozeAndNewOccurrence(t *testing.T) {
	db, user, r := reminderTestSetup(t)
	task := reminderFixture(t, db, 1, time.Now().Add(-time.Hour), "pending")
	var wg sync.WaitGroup
	var claimed atomic.Int32
	for i := 0; i < 2; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			items := reminderIDs(t, r, user, "POST", "/api/follow-up-reminders/claim", gin.H{"ids": []uint{task.ID}})
			claimed.Add(int32(len(items)))
		}()
	}
	wg.Wait()
	if claimed.Load() != 1 {
		t.Fatal("duplicate toast claims", claimed.Load())
	}
	path := fmt.Sprintf("/api/follow-up-reminders/%d/snooze", task.ID)
	if w := csRequest(r, user, "POST", path, nil); w.Code != 200 {
		t.Fatal(w.Code, w.Body.String())
	}
	if len(reminderIDs(t, r, user, "POST", "/api/follow-up-reminders/claim", gin.H{"ids": []uint{task.ID}})) != 0 {
		t.Fatal("snoozed alert replayed")
	}
	var actual models.FollowUpTask
	db.First(&actual, task.ID)
	if !actual.DueAt.Equal(task.DueAt) || actual.Status != "pending" || actual.Version != 1 {
		t.Fatal("snooze changed customer commitment")
	}
	db.Model(&models.FollowUpReminderReceipt{}).Where("user_id = ?", user.ID).Update("snoozed_until", time.Now().Add(-time.Second))
	if len(reminderIDs(t, r, user, "POST", "/api/follow-up-reminders/claim", gin.H{"ids": []uint{task.ID}})) != 1 {
		t.Fatal("snooze never woke")
	}
	db.Model(&task).Update("due_at", task.DueAt.Add(time.Minute))
	if len(reminderIDs(t, r, user, "POST", "/api/follow-up-reminders/claim", gin.H{"ids": []uint{task.ID}})) != 1 {
		t.Fatal("rescheduled occurrence missing")
	}
	db.Model(&task).Update("status", "completed")
	if got := reminderIDs(t, r, user, "GET", "/api/follow-up-reminders", nil); len(got) != 0 {
		t.Fatal("completed task still notified")
	}
	if w := csRequest(r, user, "POST", path, nil); w.Code != 404 {
		t.Fatal("completed snoozed", w.Code)
	}
}
func TestReminderClaimsDoNotCrossLoginOrWorkspace(t *testing.T) {
	db, user, r := reminderTestSetup(t)
	task := reminderFixture(t, db, 1, time.Now().Add(-time.Minute), "pending")
	foreign := reminderFixture(t, db, 2, time.Now().Add(-time.Minute), "pending")
	items := reminderIDs(t, r, user, "POST", "/api/follow-up-reminders/claim", gin.H{"ids": []uint{task.ID, foreign.ID}})
	if len(items) != 1 {
		t.Fatal("claim scope", len(items))
	}
	tid := uint(1)
	other := models.User{ID: 8, TenantID: &tid, Username: "second", Role: "cs", Active: true}
	db.Create(&other)
	db.Create(&models.UserAgentAssignment{TenantID: 1, UserID: 8, AgentID: 1})
	if len(reminderIDs(t, r, other, "POST", "/api/follow-up-reminders/claim", gin.H{"ids": []uint{task.ID}})) != 1 {
		t.Fatal("one login hid team's unassigned work from another")
	}
}
func TestReminderSettingsRequirePermissionAndExplicitDestination(t *testing.T) {
	db, user, r := reminderTestSetup(t)
	var config models.FollowUpNotificationSetting
	w := csRequest(r, user, "GET", "/api/agents/1/follow-up-notifications", nil)
	if w.Code != 200 || strings.Contains(w.Body.String(), `"enabled":true`) {
		t.Fatal("default enabled", w.Body.String())
	}
	body := gin.H{"enabled": true, "number": "6289999999999", "dashboard_url": "https://fixture.test/app"}
	if w := csRequest(r, user, "PUT", "/api/agents/2/follow-up-notifications", body); w.Code != 404 {
		t.Fatal("foreign settings write", w.Code)
	}
	db.Model(&user).Update("can_manage_ai", false)
	if w := csRequest(r, user, "PUT", "/api/agents/1/follow-up-notifications", body); w.Code != 403 {
		t.Fatal("permission bypass", w.Code)
	}
	db.Model(&user).Update("can_manage_ai", true)
	if w := csRequest(r, user, "PUT", "/api/agents/1/follow-up-notifications", body); w.Code != 200 {
		t.Fatal(w.Code, w.Body.String())
	}
	db.First(&config, "agent_id = ?", 1)
	if config.EnabledAt.IsZero() || !config.Enabled {
		t.Fatal("activation missing")
	}
	body["dashboard_url"] = "http://localhost:8181/app"
	if w := csRequest(r, user, "PUT", "/api/agents/1/follow-up-notifications", body); w.Code != 400 {
		t.Fatal("misleading phone link accepted")
	}
}
func TestReminderWhatsAppDelayGroupingRestartAndUncertain(t *testing.T) {
	db, _, _ := reminderTestSetup(t)
	now := time.Now()
	config := models.FollowUpNotificationSetting{AgentID: 1, Enabled: true, Number: "6289999999999", EnabledAt: now.Add(-time.Hour)}
	db.Create(&config)
	a := reminderFixture(t, db, 1, now.Add(-10*time.Minute), "pending")
	reminderFixture(t, db, 1, now.Add(-11*time.Minute), "pending")
	reminderFixture(t, db, 1, now.Add(-time.Minute), "pending") // still in grace
	reminderFixture(t, db, 1, now.Add(-2*time.Hour), "pending") // before activation
	sends := 0
	send := func(_ context.Context, id uint, number, text, messageID string) error {
		sends++
		if id != 1 || number != config.Number || messageID == "" || strings.Count(text, "Konfirmasi pembelian") != 2 {
			t.Fatal("wrong notification payload")
		}
		return errors.New("ambiguous transport result")
	}
	dispatchFollowUpReminderNotifications(context.Background(), db, now, func(uint) bool { return false }, send)
	if sends != 0 {
		t.Fatal("offline sent")
	}
	dispatchFollowUpReminderNotifications(context.Background(), db, now, func(uint) bool { return true }, send)
	dispatchFollowUpReminderNotifications(context.Background(), db, now, func(uint) bool { return true }, send)
	if sends != 1 {
		t.Fatal("uncertain result blindly retried", sends)
	}
	var notices []models.FollowUpNotificationDelivery
	db.Find(&notices)
	if len(notices) != 2 || notices[0].Status != "uncertain" || notices[0].MessageID != notices[1].MessageID {
		t.Fatal("group receipts invalid")
	}
	var actual models.FollowUpTask
	db.First(&actual, a.ID)
	if actual.Status != "pending" {
		t.Fatal("notification completed customer's task")
	}
}
func TestReminderWhatsAppRevalidatesBeforeSending(t *testing.T) {
	db, _, _ := reminderTestSetup(t)
	now := time.Now()
	config := models.FollowUpNotificationSetting{AgentID: 1, Enabled: true, Number: "6289999999999", EnabledAt: now.Add(-time.Hour)}
	db.Create(&config)
	task := reminderFixture(t, db, 1, now.Add(-10*time.Minute), "pending")
	checks := 0
	sends := 0
	dispatchFollowUpReminderNotifications(context.Background(), db, now, func(uint) bool {
		checks++
		if checks == 2 {
			db.Model(&task).Update("status", "completed")
		}
		return true
	}, func(context.Context, uint, string, string, string) error { sends++; return nil })
	if sends != 0 {
		t.Fatal("completed task notified")
	}
	ctx, cancel := context.WithCancel(context.Background())
	cancel()
	dispatchFollowUpReminderNotifications(ctx, db, now, func(uint) bool { return true }, func(context.Context, uint, string, string, string) error { sends++; return nil })
	if sends != 0 {
		t.Fatal("cancelled worker sent")
	}
}

func TestReminderNotificationQueueSkipsNotifiedAndSnoozedBeforeLimit(t *testing.T) {
	db, user, r := reminderTestSetup(t)
	now := time.Now()
	ids := []uint{}
	for i := 0; i < 51; i++ {
		task := reminderFixture(t, db, 1, now.Add(time.Duration(-120+i)*time.Minute), "pending")
		ids = append(ids, task.ID)
	}
	if len(reminderIDs(t, r, user, "POST", "/api/follow-up-reminders/claim", gin.H{"ids": ids[:50]})) != 50 {
		t.Fatal("first batch not claimed")
	}
	read := func() struct {
		DueCount int    `json:"due_count"`
		IDs      []uint `json:"notification_ids"`
	} {
		w := csRequest(r, user, "GET", "/api/follow-up-reminders", nil)
		var got struct {
			DueCount int    `json:"due_count"`
			IDs      []uint `json:"notification_ids"`
		}
		if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &got) != nil {
			t.Fatal(w.Body.String())
		}
		return got
	}
	got := read()
	if got.DueCount != 51 || len(got.IDs) != 1 || got.IDs[0] != ids[50] {
		t.Fatalf("old receipts starved later reminder: %+v", got)
	}
	csRequest(r, user, "POST", fmt.Sprintf("/api/follow-up-reminders/%d/snooze", ids[50]), nil)
	if got := read(); len(got.IDs) != 0 || got.DueCount != 51 {
		t.Fatal("snooze hid work or failed to defer alert", got)
	}
	db.Model(&models.FollowUpReminderReceipt{}).Where("task_id = ?", ids[50]).Update("snoozed_until", now.Add(-time.Minute))
	if got := read(); len(got.IDs) != 1 {
		t.Fatal("due snooze did not wake", got)
	}
}

func TestReminderWhatsAppReconnectConcurrencyAndReschedule(t *testing.T) {
	db, _, _ := reminderTestSetup(t)
	now := time.Now()
	db.Create(&models.FollowUpNotificationSetting{AgentID: 1, Enabled: true, Number: "6289999999999", EnabledAt: now.Add(-time.Hour)})
	task := reminderFixture(t, db, 1, now.Add(-10*time.Minute), "pending")
	var sends atomic.Int32
	send := func(context.Context, uint, string, string, string) error { sends.Add(1); return nil }
	checks := 0
	dispatchFollowUpReminderNotifications(context.Background(), db, now, func(uint) bool { checks++; return checks == 1 }, send)
	if sends.Load() != 0 {
		t.Fatal("sent after disconnect")
	}
	var claims int64
	db.Model(&models.FollowUpNotificationDelivery{}).Count(&claims)
	if claims != 0 {
		t.Fatal("known unsent occurrence cannot recover")
	}
	var wg sync.WaitGroup
	for i := 0; i < 2; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			dispatchFollowUpReminderNotifications(context.Background(), db, now, func(uint) bool { return true }, send)
		}()
	}
	wg.Wait()
	if sends.Load() != 1 {
		t.Fatal("reconnect/concurrent dispatch count", sends.Load())
	}
	var delivery models.FollowUpNotificationDelivery
	db.First(&delivery)
	if delivery.Status != "sent" || delivery.SentAt == nil {
		t.Fatal("confirmed outcome not persisted")
	}
	db.Model(&task).Update("due_at", now.Add(-6*time.Minute))
	dispatchFollowUpReminderNotifications(context.Background(), db, now, func(uint) bool { return true }, send)
	if sends.Load() != 2 {
		t.Fatal("new scheduled occurrence not sent")
	}
}

func TestReminderWhatsAppSettingsChangedBeforeSend(t *testing.T) {
	db, _, _ := reminderTestSetup(t)
	now := time.Now()
	config := models.FollowUpNotificationSetting{AgentID: 1, Enabled: true, Number: "6289999999999", EnabledAt: now.Add(-time.Hour)}
	db.Create(&config)
	reminderFixture(t, db, 1, now.Add(-10*time.Minute), "pending")
	// A database callback models a settings edit after claims but before revalidation.
	if err := db.Callback().Create().After("gorm:create").Register("reminder_disable", func(tx *gorm.DB) {
		if tx.Statement.Table == "follow_up_notification_deliveries" {
			if err := tx.Session(&gorm.Session{NewDB: true}).Model(&models.FollowUpNotificationSetting{}).Where("agent_id = ?", 1).Update("enabled", false).Error; err != nil {
				t.Error(err)
			}
		}
	}); err != nil {
		t.Fatal(err)
	}
	defer db.Callback().Create().Remove("reminder_disable")
	sends := 0
	dispatchFollowUpReminderNotifications(context.Background(), db, now, func(uint) bool { return true }, func(context.Context, uint, string, string, string) error { sends++; return nil })
	if sends != 0 {
		t.Fatal("disabled destination still notified")
	}
}

func TestReminderInternalMessagesStayScopedAndChatDeletionCleansReceipts(t *testing.T) {
	db, user, r := reminderTestSetup(t)
	if err := db.AutoMigrate(&models.HandoffNotification{}, &models.PinnedMessage{}, &models.AITurn{}, &models.InboxReadState{}); err != nil {
		t.Fatal(err)
	}
	task := reminderFixture(t, db, 1, time.Now().Add(-time.Hour), "pending")
	other := reminderFixture(t, db, 2, time.Now().Add(-time.Hour), "pending")
	db.Create(&models.FollowUpNotificationSetting{AgentID: 1, Enabled: true, Number: "6289999999999"})
	db.Create(&models.FollowUpNotificationDelivery{Key: "one", AgentID: 1, TaskID: task.ID, OccurrenceAt: task.DueAt, MessageID: "internal-one", Status: "sent"})
	db.Create(&models.FollowUpNotificationDelivery{Key: "other", AgentID: 2, TaskID: other.ID, OccurrenceAt: other.DueAt, MessageID: "internal-other", Status: "sent"})
	if !isInternalHandoffNotification(1, "internal-one") || isInternalHandoffNotification(2, "internal-one") {
		t.Fatal("internal message isolation failed")
	}
	if !isFollowUpNotificationRecipient(1, "6289999999999") || isFollowUpNotificationRecipient(2, "6289999999999") || isFollowUpNotificationRecipient(1, task.Number) {
		t.Fatal("recipient isolation failed")
	}
	reminderIDs(t, r, user, "POST", "/api/follow-up-reminders/claim", gin.H{"ids": []uint{task.ID}})
	r.DELETE("/api/agents/:id/conversation", DeleteInboxConversation)
	// Delete handler needs admin scope; this fixture is entirely in-memory.
	db.Model(&user).Update("role", "admin")
	user.Role = "admin"
	w := csRequest(r, user, "DELETE", "/api/agents/1/conversation?sender="+task.Number, nil)
	if w.Code != 200 {
		t.Fatal(w.Code, w.Body.String())
	}
	var count int64
	db.Model(&models.FollowUpReminderReceipt{}).Where("task_id = ?", task.ID).Count(&count)
	if count != 0 {
		t.Fatal("deleted chat left alert receipt")
	}
	db.Model(&models.FollowUpNotificationDelivery{}).Where("task_id = ?", task.ID).Count(&count)
	if count != 0 {
		t.Fatal("deleted chat left delivery metadata")
	}
	db.Model(&models.FollowUpNotificationDelivery{}).Where("task_id = ?", other.ID).Count(&count)
	if count != 1 {
		t.Fatal("other workspace delivery deleted")
	}
}

func TestReminderGlobalSuperadminOwnerIsNotAnUnassignedQueue(t *testing.T) {
	db, user, r := reminderTestSetup(t)
	task := reminderFixture(t, db, 1, time.Now().Add(-time.Hour), "pending")
	admin := models.User{ID: 9, Username: "global.admin", Role: "admin", IsSuperAdmin: true, Active: true}
	db.Create(&admin)
	db.Create(&models.ConversationWork{AgentID: 1, Sender: task.Number, Status: "open", AssignedUserID: admin.ID})
	if len(reminderIDs(t, r, user, "GET", "/api/follow-up-reminders", nil)) != 0 {
		t.Fatal("global admin task exposed as unassigned")
	}
	items := reminderIDs(t, r, admin, "POST", "/api/follow-up-reminders/claim", gin.H{"ids": []uint{task.ID}})
	if len(items) != 1 || items[0].AssignedUserID != admin.ID {
		t.Fatal("global admin ownership lost")
	}
}
