package v1 import ( "bytes" "context" "encoding/json" "fmt" "net/http" "net/http/httptest" "testing" "github.com/gin-gonic/gin" "github.com/stretchr/testify/require" "gorm.io/datatypes" "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" ) type dyteHandlerFakeBackend struct{} func (dyteHandlerFakeBackend) CreateMeeting(_ context.Context, _ service.DyteCredentials, _ string) (map[string]any, *service.DyteAPIError, error) { return map[string]any{"id": "meeting_id"}, nil, nil } func (dyteHandlerFakeBackend) AddParticipant(_ context.Context, _ service.DyteCredentials, _ string, _ service.DyteParticipant) (map[string]any, *service.DyteAPIError, error) { return map[string]any{"id": "participant_id", "auth_token": "json-web-token"}, nil, nil } func TestDyteIntegrationHandlerCreateMeetingReturnsMessagePayload(t *testing.T) { router, _, account, user, conversation, _ := setupDyteIntegrationHandler(t) body := bytes.NewBufferString(fmt.Sprintf(`{"conversation_id":%d}`, *conversation.DisplayID)) rec := httptest.NewRecorder() req := httptest.NewRequest(http.MethodPost, fmt.Sprintf("/api/v1/accounts/%d/integrations/dyte/create_a_meeting", account.ID), body) router.ServeHTTP(rec, req) require.Equal(t, http.StatusOK, rec.Code) payload := decodeDyteHandlerBody(t, rec) require.NotZero(t, payload["id"]) require.Equal(t, float64(*conversation.DisplayID), payload["conversation_id"]) require.Equal(t, "integrations", payload["content_type"]) require.Equal(t, "Dyte Agent has started a meeting", payload["content"]) attrs := payload["content_attributes"].(map[string]any) require.Equal(t, "dyte", attrs["type"]) require.Equal(t, "meeting_id", attrs["data"].(map[string]any)["meeting_id"]) require.Equal(t, float64(user.ID), payload["sender"].(map[string]any)["id"]) } func TestDyteIntegrationHandlerAddParticipantReturnsAuthToken(t *testing.T) { router, _, account, _, _, message := setupDyteIntegrationHandler(t) body := bytes.NewBufferString(fmt.Sprintf(`{"message_id":%d}`, message.ID)) rec := httptest.NewRecorder() req := httptest.NewRequest(http.MethodPost, fmt.Sprintf("/api/v1/accounts/%d/integrations/dyte/add_participant_to_meeting", account.ID), body) router.ServeHTTP(rec, req) require.Equal(t, http.StatusOK, rec.Code) payload := decodeDyteHandlerBody(t, rec) require.Equal(t, "participant_id", payload["id"]) require.Equal(t, "json-web-token", payload["auth_token"]) } func TestDyteIntegrationHandlerAddParticipantRejectsNonIntegrationMessage(t *testing.T) { router, db, account, _, conversation, _ := setupDyteIntegrationHandler(t) message := &model.Message{AccountID: account.ID, InboxID: conversation.InboxID, ConversationID: conversation.ID, MessageType: "outgoing", ContentType: "text", Content: "plain", Status: "sent"} require.NoError(t, db.Create(message).Error) body := bytes.NewBufferString(fmt.Sprintf(`{"message_id":%d}`, message.ID)) rec := httptest.NewRecorder() req := httptest.NewRequest(http.MethodPost, fmt.Sprintf("/api/v1/accounts/%d/integrations/dyte/add_participant_to_meeting", account.ID), body) router.ServeHTTP(rec, req) require.Equal(t, http.StatusUnprocessableEntity, rec.Code) payload := decodeDyteHandlerBody(t, rec) require.Equal(t, "Invalid message type. Action not permitted", payload["error"].(map[string]any)["error"]) } func setupDyteIntegrationHandler(t *testing.T) (*gin.Engine, *gorm.DB, *model.Account, *model.User, *model.Conversation, *model.Message) { t.Helper() gin.SetMode(gin.TestMode) db, err := gorm.Open(sqlite.Open("file::memory:?cache=shared"), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)}) require.NoError(t, err) require.NoError(t, db.AutoMigrate(&model.Account{}, &model.User{}, &model.Inbox{}, &model.Contact{}, &model.Conversation{}, &model.Message{}, &model.InboxMember{}, &model.IntegrationHook{})) t.Cleanup(func() { sqlDB, _ := db.DB(); _ = sqlDB.Close() }) account := &model.Account{Name: "Dyte Account", Locale: "en", Status: "active"} require.NoError(t, db.Create(account).Error) user := &model.User{AccountID: account.ID, Name: "Dyte Agent", Email: "dyte-agent@example.test", Password: "secret", Role: "agent"} require.NoError(t, db.Create(user).Error) inbox := &model.Inbox{AccountID: account.ID, Name: "Website", ChannelType: "web_widget", Enabled: true} require.NoError(t, db.Create(inbox).Error) require.NoError(t, db.Create(&model.InboxMember{InboxID: inbox.ID, UserID: user.ID, Role: "agent"}).Error) contact := &model.Contact{AccountID: account.ID, Name: "Visitor"} require.NoError(t, db.Create(contact).Error) displayID := uint(11) conversation := &model.Conversation{AccountID: account.ID, InboxID: inbox.ID, ContactID: contact.ID, DisplayID: &displayID, Status: "pending", ChannelType: "web_widget", Channel: "web_widget"} require.NoError(t, db.Create(conversation).Error) settings, _ := json.Marshal(map[string]any{"organization_id": "org", "api_key": "key"}) require.NoError(t, db.Create(&model.IntegrationHook{AccountID: account.ID, AppID: "dyte", HookType: model.HookType("dyte"), Settings: datatypes.JSON(settings)}).Error) attrs, _ := json.Marshal(map[string]any{"type": "dyte", "data": map[string]any{"meeting_id": "m_id"}}) message := &model.Message{AccountID: account.ID, InboxID: inbox.ID, ConversationID: conversation.ID, SenderID: &user.ID, SenderType: "user", MessageType: "outgoing", ContentType: "integrations", Content: "Join", Status: "sent", ContentAttributes: datatypes.JSON(attrs)} require.NoError(t, db.Create(message).Error) svc := service.NewDyteIntegrationService(repository.NewIntegrationHookRepo(db), repository.NewMessageRepo(db)) svc.SetBackend(dyteHandlerFakeBackend{}) handler := NewDyteIntegrationHandler(svc) router := gin.New() router.Use(func(c *gin.Context) { c.Set("user_id", user.ID) c.Set("role", "agent") c.Next() }) integrations := router.Group("/api/v1/accounts/:account_id/integrations") RegisterDyteIntegrationRoutes(integrations, handler) return router, db, account, user, conversation, message } func decodeDyteHandlerBody(t *testing.T, rec *httptest.ResponseRecorder) map[string]any { t.Helper() var payload map[string]any require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &payload)) return payload }