package handlers

import (
	"context"
	"encoding/json"
	"errors"
	"net/http/httptest"
	"reflect"
	"testing"

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

func TestWhatsAppRecipientSourcesUseOnlySavedNames(t *testing.T) {
	db := workflowTestDB(t)
	if err := db.AutoMigrate(&models.OptOut{}, &models.ChatLabel{}); err != nil {
		t.Fatal(err)
	}
	old := recipientContactNames
	t.Cleanup(func() { recipientContactNames = old })
	recipientContactNames = func(_ context.Context, id uint) (map[string]string, error) {
		if id != 1 {
			t.Fatalf("wrong WhatsApp account: %d", id)
		}
		return map[string]string{"628111111111": " Nama di Buku Kontak ", "6581234567": "Alex SG", "628333333333": "Opt-out"}, nil
	}
	for _, number := range []string{"628111111111", "628222222222", "628333333333", "6581234567", "0", "120363123456789@g.us", "12345678901234@lid"} {
		for _, value := range []any{
			&models.Contact{AgentID: 1, Number: number, Name: "Nama profil salah"},
			&models.ChatHistory{AgentID: 1, Sender: number, Message: "Halo"},
			&models.ChatLabel{AgentID: 1, LabelID: "vip", Sender: number},
		} {
			if err := db.Create(value).Error; err != nil {
				t.Fatal(err)
			}
		}
	}
	if err := db.Create(&models.OptOut{AgentID: 1, Sender: "628333333333"}).Error; err != nil {
		t.Fatal(err)
	}
	// Duplicate history must not duplicate recipients, and other agents stay private.
	db.Create(&models.ChatHistory{AgentID: 1, Sender: "628111111111", Message: "Lagi"})
	db.Create(&models.ChatHistory{AgentID: 2, Sender: "628999999999", Message: "Private"})
	db.Create(&models.ChatLabel{AgentID: 2, LabelID: "vip", Sender: "628999999999"})
	db.Create(&models.ChatLabel{AgentID: 1, LabelID: "other", Sender: "628777777777"})
	want := []services.WAContact{{Number: "628111111111", Name: "Nama di Buku Kontak"}, {Number: "628222222222", Name: ""}, {Number: "6581234567", Name: "Alex SG"}}
	for name, handler := range map[string]gin.HandlerFunc{"history": ChatContacts, "label": LabelContacts, "group-and-address-book": func(c *gin.Context) {
		respondWhatsAppRecipients(c, 1, []string{"628111111111", "+62 811-1111-111", "628222222222", "628333333333", "6581234567", "123456789@g.us"})
	}} {
		t.Run(name, func(t *testing.T) {
			w := httptest.NewRecorder()
			c, _ := gin.CreateTestContext(w)
			c.Request = httptest.NewRequest("GET", "/?label_id=vip", nil)
			c.Params = gin.Params{{Key: "id", Value: "1"}}
			c.Set("tenant_id", uint(1))
			c.Set("role", "admin")
			handler(c)
			if w.Code != 200 {
				t.Fatalf("status %d: %s", w.Code, w.Body.String())
			}
			var result struct {
				Data []services.WAContact `json:"data"`
			}
			if err := json.Unmarshal(w.Body.Bytes(), &result); err != nil {
				t.Fatal(err)
			}
			if !reflect.DeepEqual(result.Data, want) {
				t.Fatalf("recipients = %+v, want %+v", result.Data, want)
			}
		})
	}
}

func TestWhatsAppRecipientsDoNotSilentlyReplaceStoreErrorsWithProfileNames(t *testing.T) {
	workflowTestDB(t)
	old := recipientContactNames
	t.Cleanup(func() { recipientContactNames = old })
	recipientContactNames = func(context.Context, uint) (map[string]string, error) { return nil, errors.New("unavailable") }
	w := workflowRequest(t, ChatContacts, nil, gin.Params{{Key: "id", Value: "1"}})
	if w.Code != 502 {
		t.Fatalf("status = %d: %s", w.Code, w.Body.String())
	}
}
