package v1 import ( "bytes" "encoding/json" "net/http" "net/http/httptest" "strconv" "strings" "testing" "github.com/gin-gonic/gin" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "gorm.io/driver/sqlite" "gorm.io/gorm" "gorm.io/gorm/logger" "github.com/gochat/gochat/internal/model" "github.com/gochat/gochat/internal/repository" "github.com/gochat/gochat/internal/service" ) func setupInboxAgentBotRouter(handler *InboxHandler) *gin.Engine { gin.SetMode(gin.TestMode) r := gin.New() r.Use(gin.Recovery()) r.POST("/api/v1/accounts/:account_id/inboxes/:inbox_id/set_agent_bot", handler.SetAgentBot) r.GET("/api/v1/accounts/:account_id/inboxes/:inbox_id/agent_bot", handler.GetAgentBot) r.DELETE("/api/v1/accounts/:account_id/inboxes/:inbox_id/avatar", handler.DeleteAvatar) r.GET("/api/v1/accounts/:account_id/inboxes/:inbox_id/campaigns", handler.ListCampaigns) return r } func setupInboxAgentBotDB(t *testing.T) (*gin.Engine, *gorm.DB, *model.Account, *model.Inbox, *model.AgentBot) { t.Helper() dbName := "file:" + strings.ReplaceAll(t.Name(), "/", "_") + "?mode=memory&cache=shared" db, err := gorm.Open(sqlite.Open(dbName), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)}) require.NoError(t, err) t.Cleanup(func() { sqlDB, dbErr := db.DB() if dbErr == nil { sqlDB.Close() } }) require.NoError(t, db.AutoMigrate(&model.Account{}, &model.Inbox{}, &model.AgentBot{}, &model.AgentBotInbox{})) account := &model.Account{Name: "Agent bot org", Locale: "en", Active: true} require.NoError(t, db.Create(account).Error) inbox := &model.Inbox{AccountID: account.ID, Name: "Support", ChannelType: "web_widget", ChannelID: 1} require.NoError(t, db.Create(inbox).Error) bot := &model.AgentBot{AccountID: &account.ID, Name: "Triage bot", Description: "Routes chats", AvatarURL: "https://example.test/bot.png", OutgoingURL: "https://example.test/hook", BotType: "webhook", Config: json.RawMessage(`{"handoff":true}`), AccessToken: "access-token", Secret: "secret"} require.NoError(t, db.Create(bot).Error) svc := service.NewInboxService(repository.NewInboxRepo(db), repository.NewAgentBotInboxRepo(db), repository.NewAgentBotRepo(db), nil, nil, nil, nil) return setupInboxAgentBotRouter(NewInboxHandler(svc)), db, account, inbox, bot } func inboxAgentBotTestID(id uint) string { return strconv.FormatUint(uint64(id), 10) } // --- GetAgentBot tests --- func TestInboxHandler_GetAgentBot_InvalidAccountID(t *testing.T) { handler := NewInboxHandler(&service.InboxService{}) router := setupInboxAgentBotRouter(handler) w := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/api/v1/accounts/abc/inboxes/1/agent_bot", nil) router.ServeHTTP(w, req) assert.Equal(t, http.StatusBadRequest, w.Code) } func TestInboxHandler_GetAgentBot_InvalidInboxID(t *testing.T) { handler := NewInboxHandler(&service.InboxService{}) router := setupInboxAgentBotRouter(handler) w := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/api/v1/accounts/1/inboxes/abc/agent_bot", nil) router.ServeHTTP(w, req) assert.Equal(t, http.StatusBadRequest, w.Code) } func TestInboxHandler_GetAgentBot_ValidIDs_ZeroService(t *testing.T) { handler := NewInboxHandler(&service.InboxService{}) router := setupInboxAgentBotRouter(handler) w := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/api/v1/accounts/1/inboxes/1/agent_bot", nil) router.ServeHTTP(w, req) // Zero service will panic on method call; Recovery middleware catches it → 500 assert.True(t, w.Code == http.StatusUnprocessableEntity || w.Code == http.StatusOK) } func TestInboxHandler_SetAndGetAgentBot_ChatwootPayload(t *testing.T) { router, _, account, inbox, bot := setupInboxAgentBotDB(t) body, _ := json.Marshal(map[string]uint{"agent_bot": bot.ID}) w := httptest.NewRecorder() req, _ := http.NewRequest(http.MethodPost, "/api/v1/accounts/"+inboxAgentBotTestID(account.ID)+"/inboxes/"+inboxAgentBotTestID(inbox.ID)+"/set_agent_bot", bytes.NewReader(body)) req.Header.Set("Content-Type", "application/json") router.ServeHTTP(w, req) require.Equal(t, http.StatusOK, w.Code) assert.Empty(t, w.Body.String(), "Chatwoot set_agent_bot responds head :ok") w = httptest.NewRecorder() req, _ = http.NewRequest(http.MethodGet, "/api/v1/accounts/"+inboxAgentBotTestID(account.ID)+"/inboxes/"+inboxAgentBotTestID(inbox.ID)+"/agent_bot", nil) router.ServeHTTP(w, req) require.Equal(t, http.StatusOK, w.Code) var resp map[string]map[string]interface{} require.NoError(t, json.Unmarshal(w.Body.Bytes(), &resp)) agentBot := resp["agent_bot"] assert.Equal(t, float64(bot.ID), agentBot["id"]) assert.Equal(t, bot.Name, agentBot["name"]) assert.Equal(t, bot.AvatarURL, agentBot["thumbnail"]) assert.Equal(t, bot.OutgoingURL, agentBot["outgoing_url"]) assert.Equal(t, bot.BotType, agentBot["bot_type"]) assert.NotContains(t, agentBot, "avatar_url") } func TestInboxHandler_SetAgentBot_NullDisconnectsWithHeadOK(t *testing.T) { router, db, account, inbox, bot := setupInboxAgentBotDB(t) require.NoError(t, db.Create(&model.AgentBotInbox{AccountID: &account.ID, InboxID: inbox.ID, AgentBotID: bot.ID, Status: model.AgentBotInboxActive}).Error) w := httptest.NewRecorder() req, _ := http.NewRequest(http.MethodPost, "/api/v1/accounts/"+inboxAgentBotTestID(account.ID)+"/inboxes/"+inboxAgentBotTestID(inbox.ID)+"/set_agent_bot", bytes.NewReader([]byte(`{"agent_bot":null}`))) req.Header.Set("Content-Type", "application/json") router.ServeHTTP(w, req) require.Equal(t, http.StatusOK, w.Code) assert.Empty(t, w.Body.String()) var count int64 require.NoError(t, db.Model(&model.AgentBotInbox{}).Where("inbox_id = ?", inbox.ID).Count(&count).Error) assert.Equal(t, int64(0), count) w = httptest.NewRecorder() req, _ = http.NewRequest(http.MethodGet, "/api/v1/accounts/"+inboxAgentBotTestID(account.ID)+"/inboxes/"+inboxAgentBotTestID(inbox.ID)+"/agent_bot", nil) router.ServeHTTP(w, req) require.Equal(t, http.StatusOK, w.Code) assert.JSONEq(t, `{"agent_bot":{}}`, w.Body.String()) } // --- DeleteAvatar tests --- func TestInboxHandler_DeleteAvatar_InvalidAccountID(t *testing.T) { handler := NewInboxHandler(&service.InboxService{}) router := setupInboxAgentBotRouter(handler) w := httptest.NewRecorder() req, _ := http.NewRequest("DELETE", "/api/v1/accounts/abc/inboxes/1/avatar", nil) router.ServeHTTP(w, req) assert.Equal(t, http.StatusBadRequest, w.Code) } func TestInboxHandler_DeleteAvatar_InvalidInboxID(t *testing.T) { handler := NewInboxHandler(&service.InboxService{}) router := setupInboxAgentBotRouter(handler) w := httptest.NewRecorder() req, _ := http.NewRequest("DELETE", "/api/v1/accounts/1/inboxes/abc/avatar", nil) router.ServeHTTP(w, req) assert.Equal(t, http.StatusBadRequest, w.Code) } func TestInboxHandler_DeleteAvatar_ValidIDs_ZeroService(t *testing.T) { handler := NewInboxHandler(&service.InboxService{}) router := setupInboxAgentBotRouter(handler) w := httptest.NewRecorder() req, _ := http.NewRequest("DELETE", "/api/v1/accounts/1/inboxes/1/avatar", nil) router.ServeHTTP(w, req) // Zero service will panic on method call; Recovery middleware catches it → 500 assert.True(t, w.Code == http.StatusUnprocessableEntity || w.Code == http.StatusOK) } // --- ListCampaigns tests --- func TestInboxHandler_ListCampaigns_InvalidAccountID(t *testing.T) { handler := NewInboxHandler(&service.InboxService{}) router := setupInboxAgentBotRouter(handler) w := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/api/v1/accounts/abc/inboxes/1/campaigns", nil) router.ServeHTTP(w, req) assert.Equal(t, http.StatusBadRequest, w.Code) } func TestInboxHandler_ListCampaigns_InvalidInboxID(t *testing.T) { handler := NewInboxHandler(&service.InboxService{}) router := setupInboxAgentBotRouter(handler) w := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/api/v1/accounts/1/inboxes/abc/campaigns", nil) router.ServeHTTP(w, req) assert.Equal(t, http.StatusBadRequest, w.Code) } func TestInboxHandler_ListCampaigns_ValidIDs_ZeroService(t *testing.T) { handler := NewInboxHandler(&service.InboxService{}) router := setupInboxAgentBotRouter(handler) w := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/api/v1/accounts/1/inboxes/1/campaigns", nil) router.ServeHTTP(w, req) // Zero service will panic on method call; Recovery middleware catches it → 500 assert.True(t, w.Code == http.StatusUnprocessableEntity || w.Code == http.StatusOK) }