package handlers

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

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

func followUpTaskTestSetup(t *testing.T) (*gorm.DB, models.User, *gin.Engine) {
	db, user := csWorkspaceDB(t)
	if err := db.AutoMigrate(&models.FollowUpTask{}, &models.OptOut{}); err != nil {
		t.Fatal(err)
	}
	r := gin.New()
	r.Use(AuthMiddleware(), CSRouteGuard())
	r.GET("/api/agents/:id/follow-up-tasks", ListFollowUpTasks)
	r.POST("/api/agents/:id/follow-up-tasks", CreateFollowUpTask)
	r.GET("/api/agents/:id/follow-up-tasks/:taskID", GetFollowUpTask)
	r.PUT("/api/agents/:id/follow-up-tasks/:taskID", UpdateFollowUpTask)
	r.POST("/api/agents/:id/follow-up-tasks/:taskID/finish", FinishFollowUpTask)
	r.POST("/api/agents/:id/follow-up-tasks/:taskID/send", SendFollowUpTask)
	r.POST("/api/agents/:id/follow-up-tasks/:taskID/draft", GenerateFollowUpTaskDraft)
	return db, user, r
}

func TestFollowUpTasksAccessCreationAndReviewVersion(t *testing.T) {
	db, user, r := followUpTaskTestSetup(t)
	body := map[string]any{"number": "081234567890", "reason": "Melanjutkan konsultasi", "draft": "Halo kak, boleh dilanjutkan?", "due_at": time.Now().Add(time.Hour), "request_id": "unique-client-request-1"}
	for _, method := range []string{"GET", "POST"} {
		if w := csRequest(r, user, method, "/api/agents/2/follow-up-tasks", body); w.Code != 404 {
			t.Fatal("foreign number access", w.Code)
		}
	}
	for i := 0; i < 2; i++ {
		if w := csRequest(r, user, "POST", "/api/agents/1/follow-up-tasks", body); w.Code != 201 {
			t.Fatal(w.Code, w.Body.String())
		}
	}
	var tasks []models.FollowUpTask
	db.Find(&tasks)
	if len(tasks) != 1 {
		t.Fatal("duplicate creation", len(tasks))
	}
	task := tasks[0]
	path := fmt.Sprintf("/api/agents/1/follow-up-tasks/%d", task.ID)
	body["version"] = task.Version
	if w := csRequest(r, user, "PUT", path, body); w.Code != 200 {
		t.Fatal(w.Code, w.Body.String())
	}
	if w := csRequest(r, user, "PUT", path, body); w.Code != 409 {
		t.Fatal("stale edit overwrote task")
	}
	for _, suffix := range []string{"", "/draft", "/send", "/finish"} {
		method := "POST"
		if suffix == "" {
			method = "GET"
		}
		if w := csRequest(r, user, method, fmt.Sprintf("/api/agents/2/follow-up-tasks/%d%s", task.ID, suffix), body); w.Code != 404 {
			t.Fatal("unassigned action", suffix, w.Code)
		}
	}
	db.Where("user_id = ?", user.ID).Delete(&models.UserAgentAssignment{})
	if w := csRequest(r, user, "GET", path, nil); w.Code != 404 {
		t.Fatal("revoked assignment still reads task")
	}
}

func TestFollowUpTaskSendRejectsChangedContextOptOutAndDuplicate(t *testing.T) {
	db, user, r := followUpTaskTestSetup(t)
	task := models.FollowUpTask{AgentID: 1, Number: "6281234567890", Reason: "Lanjut", DueAt: time.Now(), Status: "pending", Source: "manual", SourceKey: "send-test", Version: 1}
	db.Create(&task)
	oldConnected, oldSend := followUpTaskConnected, sendFollowUpTaskText
	t.Cleanup(func() { followUpTaskConnected, sendFollowUpTaskText = oldConnected, oldSend })
	followUpTaskConnected = func(uint) bool { return true }
	var sends atomic.Int32
	sendFollowUpTaskText = func(uint, string, string) (string, error) { sends.Add(1); return "fixture-sent-id", nil }
	ctx, _ := services.ReadFollowUpContext(context.Background(), 1, task.Number)
	body := map[string]any{"version": 1, "draft": "Halo kak, boleh kita lanjutkan?", "context_token": ctx.Token}
	path := fmt.Sprintf("/api/agents/1/follow-up-tasks/%d/send", task.ID)
	db.Create(&models.ChatHistory{AgentID: 1, Sender: task.Number, Message: "Saya sudah beli", CreatedAt: time.Now()})
	if w := csRequest(r, user, "POST", path, body); w.Code != 409 {
		t.Fatal("stale context sent", w.Code)
	}
	ctx, _ = services.ReadFollowUpContext(context.Background(), 1, task.Number)
	body["context_token"] = ctx.Token
	opt := models.OptOut{AgentID: 1, Sender: task.Number}
	db.Create(&opt)
	if w := csRequest(r, user, "POST", path, body); w.Code != 409 {
		t.Fatal("optout sent", w.Code)
	}
	db.Delete(&opt)
	// Two operators pressing Send at once still perform one external side effect.
	var wg sync.WaitGroup
	responses := make(chan *httptest.ResponseRecorder, 2)
	for i := 0; i < 2; i++ {
		wg.Add(1)
		go func() { defer wg.Done(); responses <- csRequest(r, user, "POST", path, body) }()
	}
	wg.Wait()
	close(responses)
	for w := range responses {
		if w.Code != 200 && w.Code != 409 {
			t.Fatal(w.Code, w.Body.String())
		}
	}
	if sends.Load() != 1 {
		t.Fatal("duplicate WA send", sends.Load())
	}
	if w := csRequest(r, user, "POST", path, body); w.Code != 200 {
		t.Fatal("idempotent completed response", w.Code)
	}
	if sends.Load() != 1 {
		t.Fatal("completed task resent")
	}
	db.First(&task, task.ID)
	if task.Status != "completed" || task.Outcome != "sent" {
		t.Fatal(task.Status, task.Outcome)
	}
	var row models.ChatHistory
	db.Where("wa_msg_id = ?", "fixture-sent-id").First(&row)
	if !row.FromHuman || row.Reply != body["draft"] {
		t.Fatal("send absent from Inbox")
	}
}

func TestFollowUpTaskUncertainDeliveryCannotBeRetried(t *testing.T) {
	db, user, r := followUpTaskTestSetup(t)
	task := models.FollowUpTask{AgentID: 1, Number: "6281234567890", Reason: "Lanjut", DueAt: time.Now(), Status: "pending", Source: "manual", SourceKey: "uncertain-test", Version: 1}
	db.Create(&task)
	oldConnected, oldSend := followUpTaskConnected, sendFollowUpTaskText
	t.Cleanup(func() { followUpTaskConnected, sendFollowUpTaskText = oldConnected, oldSend })
	followUpTaskConnected = func(uint) bool { return true }
	count := 0
	sendFollowUpTaskText = func(uint, string, string) (string, error) { count++; return "", errors.New("lost acknowledgement") }
	ctx, _ := services.ReadFollowUpContext(context.Background(), 1, task.Number)
	body := map[string]any{"version": 1, "draft": "Halo kak", "context_token": ctx.Token}
	path := fmt.Sprintf("/api/agents/1/follow-up-tasks/%d/send", task.ID)
	if w := csRequest(r, user, "POST", path, body); w.Code != 502 {
		t.Fatal(w.Code)
	}
	body["version"] = 2
	if w := csRequest(r, user, "POST", path, body); w.Code != 409 {
		t.Fatal("uncertain message retried", w.Code)
	}
	if count != 1 {
		t.Fatal("uncertain delivery repeated")
	}
}

func TestFollowUpTaskRechecksIncomingWhilePreparingSend(t *testing.T) {
	db, user, r := followUpTaskTestSetup(t)
	task := models.FollowUpTask{AgentID: 1, Number: "6281234567890", Reason: "Lanjut", DueAt: time.Now(), Status: "pending", Source: "manual", SourceKey: "context-race-test", Version: 1}
	db.Create(&task)
	oldConnected, oldSend := followUpTaskConnected, sendFollowUpTaskText
	t.Cleanup(func() { followUpTaskConnected, sendFollowUpTaskText = oldConnected, oldSend })
	followUpTaskConnected = func(uint) bool {
		db.Create(&models.ChatHistory{AgentID: 1, Sender: task.Number, Message: "Tidak perlu dilanjutkan ya", CreatedAt: time.Now()})
		return true
	}
	sendFollowUpTaskText = func(uint, string, string) (string, error) { t.Fatal("outdated draft sent"); return "", nil }
	ctx, _ := services.ReadFollowUpContext(context.Background(), 1, task.Number)
	body := map[string]any{"version": 1, "draft": "Halo kak, boleh kita lanjutkan?", "context_token": ctx.Token}
	path := fmt.Sprintf("/api/agents/1/follow-up-tasks/%d/send", task.ID)
	if w := csRequest(r, user, "POST", path, body); w.Code != 409 {
		t.Fatal(w.Code, w.Body.String())
	}
	var current models.FollowUpTask
	db.First(&current, task.ID)
	if current.Status != "pending" || current.Version != 2 {
		t.Fatal("review was not invalidated", current.Status, current.Version)
	}
}

func TestFollowUpTaskListsUseWIBAndDoNotSendWhenDue(t *testing.T) {
	db, user, r := followUpTaskTestSetup(t)
	now := time.Now().In(services.FollowUpLocation)
	tomorrow := time.Date(now.Year(), now.Month(), now.Day()+1, 0, 0, 0, 0, services.FollowUpLocation)
	for i, due := range []time.Time{tomorrow.Add(-time.Minute), tomorrow} {
		db.Create(&models.FollowUpTask{AgentID: 1, Number: "6281234567890", Reason: "Lanjut", DueAt: due, Status: "pending", Source: "manual", SourceKey: fmt.Sprint(i), Version: 1})
	}
	w := csRequest(r, user, "GET", "/api/agents/1/follow-up-tasks?view=today", nil)
	var out struct {
		Data   []models.FollowUpTask `json:"data"`
		Counts map[string]int64      `json:"counts"`
	}
	if json.Unmarshal(w.Body.Bytes(), &out) != nil || w.Code != 200 || len(out.Data) != 1 || out.Counts["today"] != 1 || out.Counts["scheduled"] != 1 {
		t.Fatal(w.Code, w.Body.String())
	}
	// Merely reaching the reminder time has no connection to the drip worker.
	if out.Data[0].Status != "pending" {
		t.Fatal("reminder sent without review")
	}
}
