package v1 import ( "bytes" "context" "encoding/json" "fmt" "net/http" "net/http/httptest" "testing" "github.com/gin-gonic/gin" "github.com/gochat/gochat/internal/llm" "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" ) type mockRespHandlerLLM struct { response *llm.ChatResponse err error } func (m *mockRespHandlerLLM) ChatCompletion(_ context.Context, _ llm.ChatRequest) (*llm.ChatResponse, error) { return m.response, m.err } func (m *mockRespHandlerLLM) CreateEmbedding(_ context.Context, _ llm.EmbeddingRequest) (*llm.EmbeddingResponse, error) { return nil, nil } func (m *mockRespHandlerLLM) ChatCompletionStream(_ context.Context, _ llm.ChatRequest, _ func(llm.StreamChunk) error) error { return nil } func setupAssistantResponseHandlerTest(t *testing.T, mockLLM llm.Provider) (*CaptainAssistantResponseHandler, *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.CaptainPreference{}, &model.CaptainAssistant{}, &model.Conversation{}, &model.Message{}, &model.Inbox{}, &model.Contact{}, )) assistantRepo := repository.NewCaptainAssistantRepo(db) responseRepo := repository.NewCaptainAssistantResponseRepo(db) convRepo := repository.NewConversationRepo(db) msgRepo := repository.NewMessageRepo(db) prefRepo := repository.NewCaptainPreferenceRepo(db) svc := service.NewCaptainAssistantResponseService(assistantRepo, responseRepo, convRepo, msgRepo, prefRepo, mockLLM) handler := NewCaptainAssistantResponseHandler(svc) return handler, db } func seedAssistantResponseData(t *testing.T, db *gorm.DB) (*model.Conversation, *model.CaptainAssistant) { t.Helper() inbox := &model.Inbox{AccountID: 1, Name: "Inbox", ChannelType: "web_widget"} require.NoError(t, db.Create(inbox).Error) conv := &model.Conversation{AccountID: 1, InboxID: inbox.ID, Status: "open"} require.NoError(t, db.Create(conv).Error) msg := &model.Message{ConversationID: conv.ID, AccountID: 1, InboxID: inbox.ID, SenderType: "contact", Content: "reset password?", ContentType: "text", MessageType: "incoming"} require.NoError(t, db.Create(msg).Error) cfg := &model.AssistantConfig{Instructions: "Be helpful", Temperature: 0.7} cfgJSON, _ := json.Marshal(cfg) assistant := &model.CaptainAssistant{AccountID: 1, Name: "Bot", Config: cfgJSON, Status: model.AssistantStatusActive} require.NoError(t, db.Create(assistant).Error) return conv, assistant } func TestCaptainAssistantResponseHandler_ProcessResponse(t *testing.T) { mockLLM := &mockRespHandlerLLM{ response: &llm.ChatResponse{ Choices: []llm.ChatChoice{ {Message: llm.ChatMessage{Role: "assistant", Content: "You can reset your password in Settings."}}, }, }, } handler, db := setupAssistantResponseHandlerTest(t, mockLLM) conv, assistant := seedAssistantResponseData(t, db) body := map[string]interface{}{ "conversation_id": conv.ID, "assistant_id": assistant.ID, "send_message": false, } bodyBytes, _ := json.Marshal(body) w := httptest.NewRecorder() c, _ := gin.CreateTestContext(w) c.Params = gin.Params{{Key: "id", Value: "1"}} c.Request = httptest.NewRequest(http.MethodPost, "/api/v1/accounts/1/captain/assistant_responses/process", bytes.NewReader(bodyBytes)) c.Request.Header.Set("Content-Type", "application/json") handler.ProcessResponse(c) assert.Equal(t, http.StatusOK, w.Code) var resp handlerTestResponse require.NoError(t, json.Unmarshal(w.Body.Bytes(), &resp)) assert.True(t, resp.Success) } func TestCaptainAssistantResponseHandler_ProcessResponse_InvalidAccountID(t *testing.T) { mockLLM := &mockRespHandlerLLM{} handler, _ := setupAssistantResponseHandlerTest(t, mockLLM) w := httptest.NewRecorder() c, _ := gin.CreateTestContext(w) c.Params = gin.Params{{Key: "id", Value: "invalid"}} c.Request = httptest.NewRequest(http.MethodPost, "/api/v1/accounts/invalid/captain/assistant_responses/process", nil) c.Request.Header.Set("Content-Type", "application/json") handler.ProcessResponse(c) assert.Equal(t, http.StatusBadRequest, w.Code) } func TestCaptainAssistantResponseHandler_ProcessResponse_LLMError(t *testing.T) { mockLLM := &mockRespHandlerLLM{err: fmt.Errorf("LLM unavailable")} handler, db := setupAssistantResponseHandlerTest(t, mockLLM) conv, assistant := seedAssistantResponseData(t, db) body := map[string]interface{}{ "conversation_id": conv.ID, "assistant_id": assistant.ID, "send_message": false, } bodyBytes, _ := json.Marshal(body) w := httptest.NewRecorder() c, _ := gin.CreateTestContext(w) c.Params = gin.Params{{Key: "id", Value: "1"}} c.Request = httptest.NewRequest(http.MethodPost, "/api/v1/accounts/1/captain/assistant_responses/process", bytes.NewReader(bodyBytes)) c.Request.Header.Set("Content-Type", "application/json") handler.ProcessResponse(c) assert.Equal(t, http.StatusUnprocessableEntity, w.Code) }