package v1 import ( "bytes" "encoding/json" "fmt" "net/http" "net/http/httptest" "strconv" "testing" "github.com/gin-gonic/gin" "github.com/gochat/gochat/internal/model" "github.com/gochat/gochat/internal/repository" "github.com/gochat/gochat/internal/service" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "gorm.io/driver/sqlite" "gorm.io/gorm" ) func setupCaptainAssistantHandlerTest(t *testing.T) (*gin.Engine, *gorm.DB) { t.Helper() gin.SetMode(gin.TestMode) dbName := fmt.Sprintf("file:%s?mode=memory&cache=private", t.Name()) db, err := gorm.Open(sqlite.Open(dbName), &gorm.Config{}) require.NoError(t, err) require.NoError(t, db.AutoMigrate( &model.Account{}, &model.Inbox{}, &model.CaptainAssistant{}, &model.CaptainInbox{}, )) t.Cleanup(func() { sqlDB, _ := db.DB() sqlDB.Close() }) assistantRepo := repository.NewCaptainAssistantRepo(db) inboxRepo := repository.NewCaptainInboxRepo(db) documentRepo := repository.NewCaptainDocumentRepo(db) responseRepo := repository.NewCaptainAssistantResponseRepo(db) svc := service.NewCaptainAssistantService(assistantRepo, inboxRepo, documentRepo, responseRepo, nil) handler := NewCaptainAssistantHandler(svc) router := gin.New() assistants := router.Group("/api/v1/accounts/:account_id/captain/assistants") assistants.GET("/", handler.List) assistants.POST("/", handler.Create) assistants.GET("/tools", handler.Tools) assistants.GET("/:assistant_id", handler.Get) assistants.PUT("/:assistant_id", handler.Update) assistants.DELETE("/:assistant_id", handler.Delete) assistants.GET("/:assistant_id/inboxes", handler.ListInboxes) assistants.POST("/:assistant_id/inboxes", handler.AssociateInbox) assistants.DELETE("/:assistant_id/inboxes/:inbox_id", handler.DissociateInbox) return router, db } func seedCaptainAssistantAccount(t *testing.T, db *gorm.DB, name string) *model.Account { t.Helper() account := &model.Account{Name: name, Locale: "en", Active: true} require.NoError(t, db.Create(account).Error) return account } func captainAssistantJSONRequest(t *testing.T, router *gin.Engine, method, path string, body any) *httptest.ResponseRecorder { t.Helper() var reader *bytes.Reader if body == nil { reader = bytes.NewReader(nil) } else { payload, err := json.Marshal(body) require.NoError(t, err) reader = bytes.NewReader(payload) } w := httptest.NewRecorder() req := httptest.NewRequest(method, path, reader) req.Header.Set("Content-Type", "application/json") router.ServeHTTP(w, req) return w } func TestCaptainAssistantHandler_CRUDUsesChatwootPayloadShape(t *testing.T) { router, db := setupCaptainAssistantHandlerTest(t) account := seedCaptainAssistantAccount(t, db, "Captain Org") basePath := "/api/v1/accounts/" + strconv.FormatUint(uint64(account.ID), 10) + "/captain/assistants" createBody := map[string]any{ "assistant": map[string]any{ "name": "Fin", "description": "Support copilot", "config": map[string]any{ "product_name": "GoChat", "temperature": 0.2, }, "guardrails": []string{"never ask for passwords"}, "response_guidelines": []string{"be concise"}, }, } w := captainAssistantJSONRequest(t, router, http.MethodPost, basePath+"/", createBody) assert.Equal(t, http.StatusOK, w.Code) var created map[string]any require.NoError(t, json.Unmarshal(w.Body.Bytes(), &created)) assert.NotContains(t, created, "success") assert.NotContains(t, created, "data") assert.Equal(t, float64(account.ID), created["account_id"]) assert.Equal(t, "Fin", created["name"]) assert.Equal(t, "Support copilot", created["description"]) assert.Equal(t, "GoChat", created["config"].(map[string]any)["product_name"]) assistantID := uint(created["id"].(float64)) w = captainAssistantJSONRequest(t, router, http.MethodGet, basePath+"/", nil) assert.Equal(t, http.StatusOK, w.Code) var listResp map[string]any require.NoError(t, json.Unmarshal(w.Body.Bytes(), &listResp)) assert.Len(t, listResp["payload"], 1) assert.Equal(t, float64(1), listResp["meta"].(map[string]any)["total_count"]) assert.Equal(t, float64(1), listResp["meta"].(map[string]any)["page"]) updateBody := map[string]any{"assistant": map[string]any{"name": "Fin Prime", "description": "Updated"}} w = captainAssistantJSONRequest(t, router, http.MethodPut, fmt.Sprintf("%s/%d", basePath, assistantID), updateBody) assert.Equal(t, http.StatusOK, w.Code) var updated map[string]any require.NoError(t, json.Unmarshal(w.Body.Bytes(), &updated)) assert.Equal(t, "Fin Prime", updated["name"]) assert.Equal(t, "Updated", updated["description"]) w = captainAssistantJSONRequest(t, router, http.MethodGet, fmt.Sprintf("%s/%d", basePath, assistantID), nil) assert.Equal(t, http.StatusOK, w.Code) w = captainAssistantJSONRequest(t, router, http.MethodDelete, fmt.Sprintf("%s/%d", basePath, assistantID), nil) assert.Equal(t, http.StatusNoContent, w.Code) } func TestCaptainAssistantHandler_AccountScopedShowAndInboxBinding(t *testing.T) { router, db := setupCaptainAssistantHandlerTest(t) account := seedCaptainAssistantAccount(t, db, "Account One") otherAccount := seedCaptainAssistantAccount(t, db, "Account Two") assistant := &model.CaptainAssistant{AccountID: account.ID, Name: "Fin", Description: "Support", Config: json.RawMessage(`{}`), Status: model.AssistantStatusActive} require.NoError(t, db.Create(assistant).Error) inbox := &model.Inbox{AccountID: account.ID, Name: "Primary", ChannelType: "web_widget"} require.NoError(t, db.Create(inbox).Error) otherInbox := &model.Inbox{AccountID: otherAccount.ID, Name: "Other", ChannelType: "web_widget"} require.NoError(t, db.Create(otherInbox).Error) basePath := "/api/v1/accounts/" + strconv.FormatUint(uint64(account.ID), 10) + "/captain/assistants" otherBasePath := "/api/v1/accounts/" + strconv.FormatUint(uint64(otherAccount.ID), 10) + "/captain/assistants" w := captainAssistantJSONRequest(t, router, http.MethodGet, fmt.Sprintf("%s/%d", otherBasePath, assistant.ID), nil) assert.Equal(t, http.StatusNotFound, w.Code) w = captainAssistantJSONRequest(t, router, http.MethodGet, basePath+"/tools", nil) assert.Equal(t, http.StatusOK, w.Code) var tools []map[string]any require.NoError(t, json.Unmarshal(w.Body.Bytes(), &tools)) assert.Len(t, tools, 7) assert.Equal(t, "add_contact_note", tools[0]["id"]) bindBody := map[string]any{"inbox": map[string]any{"inbox_id": inbox.ID}} w = captainAssistantJSONRequest(t, router, http.MethodPost, fmt.Sprintf("%s/%d/inboxes", basePath, assistant.ID), bindBody) assert.Equal(t, http.StatusOK, w.Code) var bound map[string]any require.NoError(t, json.Unmarshal(w.Body.Bytes(), &bound)) assert.Equal(t, float64(inbox.ID), bound["id"]) assert.NotContains(t, bound, "success") w = captainAssistantJSONRequest(t, router, http.MethodGet, fmt.Sprintf("%s/%d/inboxes", basePath, assistant.ID), nil) assert.Equal(t, http.StatusOK, w.Code) var inboxList map[string]any require.NoError(t, json.Unmarshal(w.Body.Bytes(), &inboxList)) assert.Len(t, inboxList["payload"], 1) wrongBindBody := map[string]any{"inbox": map[string]any{"inbox_id": otherInbox.ID}} w = captainAssistantJSONRequest(t, router, http.MethodPost, fmt.Sprintf("%s/%d/inboxes", basePath, assistant.ID), wrongBindBody) assert.Equal(t, http.StatusNotFound, w.Code) w = captainAssistantJSONRequest(t, router, http.MethodDelete, fmt.Sprintf("%s/%d/inboxes/%d", otherBasePath, assistant.ID, inbox.ID), nil) assert.Equal(t, http.StatusNotFound, w.Code) w = captainAssistantJSONRequest(t, router, http.MethodDelete, fmt.Sprintf("%s/%d/inboxes/%d", basePath, assistant.ID, inbox.ID), nil) assert.Equal(t, http.StatusNoContent, w.Code) }