package v1 import ( "bytes" "context" "encoding/json" "fmt" "mime/multipart" "net/http" "net/http/httptest" "strconv" "testing" "github.com/gin-gonic/gin" "github.com/stretchr/testify/require" "gorm.io/driver/sqlite" "gorm.io/gorm" "gorm.io/gorm/logger" "github.com/gochat/gochat/internal/model" channelmodel "github.com/gochat/gochat/internal/model/channel" "github.com/gochat/gochat/internal/repository" "github.com/gochat/gochat/internal/service" ) type fakeHandlerWhatsAppCallProvider struct{} func (fakeHandlerWhatsAppCallProvider) InitiateCall(context.Context, *channelmodel.ChannelWhatsApp, string, string) (string, error) { return "wacid_handler", nil } func (fakeHandlerWhatsAppCallProvider) PreAcceptCall(context.Context, *channelmodel.ChannelWhatsApp, string, string) error { return nil } func (fakeHandlerWhatsAppCallProvider) AcceptCall(context.Context, *channelmodel.ChannelWhatsApp, string, string) error { return nil } func (fakeHandlerWhatsAppCallProvider) RejectCall(context.Context, *channelmodel.ChannelWhatsApp, string) error { return nil } func (fakeHandlerWhatsAppCallProvider) TerminateCall(context.Context, *channelmodel.ChannelWhatsApp, string) error { return nil } func (fakeHandlerWhatsAppCallProvider) SendCallPermissionRequest(context.Context, *channelmodel.ChannelWhatsApp, string, string) (string, error) { return "wamid.req", nil } func setupWhatsAppCallHandlerTest(t *testing.T) (*gin.Engine, *gorm.DB, *model.Account, *model.Conversation) { t.Helper() gin.SetMode(gin.TestMode) db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)}) require.NoError(t, err) require.NoError(t, db.AutoMigrate(&model.Account{}, &model.User{}, &model.Inbox{}, &model.InboxMember{}, &model.CustomRole{}, &model.Contact{}, &model.Conversation{}, &model.Call{}, &model.Message{}, &model.Attachment{}, &channelmodel.ChannelWhatsApp{})) account := &model.Account{Name: "Voice Account", Status: "active"} require.NoError(t, db.Create(account).Error) inbox := &model.Inbox{AccountID: account.ID, Name: "WhatsApp", ChannelType: "whatsapp", ChannelID: 1, ChannelConfig: `{"voice_enabled":true}`} require.NoError(t, db.Create(inbox).Error) channel := &channelmodel.ChannelWhatsApp{AccountID: account.ID, InboxID: inbox.ID, PhoneNumber: "+15550000000", PhoneNumberID: "phone-1", BusinessAccountID: "waba-1", AccessToken: "token", Provider: "whatsapp_cloud", ProviderConfig: `{"calling_enabled":true}`} require.NoError(t, db.Create(channel).Error) inbox.ChannelID = channel.ID require.NoError(t, db.Save(inbox).Error) contact := &model.Contact{AccountID: account.ID, Name: "Ada", PhoneNumber: "+15551234567"} require.NoError(t, db.Create(contact).Error) displayID := uint(42) conversation := &model.Conversation{AccountID: account.ID, InboxID: inbox.ID, ContactID: contact.ID, DisplayID: &displayID, Status: "open", ChannelType: "whatsapp", Channel: "whatsapp"} require.NoError(t, db.Create(conversation).Error) handler := NewWhatsAppCallHandler(service.NewWhatsAppCallService(repository.NewWhatsAppCallRepo(db), fakeHandlerWhatsAppCallProvider{})) router := gin.New() router.Use(func(c *gin.Context) { c.Set("user_id", uint(7)) c.Set("role", "administrator") c.Next() }) router.GET("/api/v1/accounts/:account_id/calls", handler.Index) router.GET("/api/v1/accounts/:account_id/whatsapp_calls/:id", handler.Show) router.POST("/api/v1/accounts/:account_id/whatsapp_calls/initiate", handler.Initiate) router.POST("/api/v1/accounts/:account_id/whatsapp_calls/:id/accept", handler.Accept) router.POST("/api/v1/accounts/:account_id/whatsapp_calls/:id/reject", handler.Reject) router.POST("/api/v1/accounts/:account_id/whatsapp_calls/:id/terminate", handler.Terminate) router.POST("/api/v1/accounts/:account_id/whatsapp_calls/:id/upload_recording", handler.UploadRecording) return router, db, account, conversation } func TestWhatsAppCallHandler_IndexMatchesChatwootCallsEnvelope(t *testing.T) { router, db, account, conversation := setupWhatsAppCallHandlerTest(t) call := &model.Call{AccountID: account.ID, InboxID: conversation.InboxID, ConversationID: conversation.ID, ContactID: conversation.ContactID, Provider: "whatsapp", Direction: "incoming", ProviderCallID: "wacid_index", Status: "in_progress", Duration: 12, CallerType: "Contact", CallerID: conversation.ContactID, CallDirection: "inbound", Transcript: "hello"} require.NoError(t, db.Create(call).Error) w := httptest.NewRecorder() req := httptest.NewRequest(http.MethodGet, fmt.Sprintf("/api/v1/accounts/%d/calls?status=in-progress&direction=inbound", account.ID), nil) router.ServeHTTP(w, req) require.Equal(t, http.StatusOK, w.Code, w.Body.String()) payload := whatsappDecodeMap(t, w.Body.Bytes()) meta := payload["meta"].(map[string]any) require.Equal(t, float64(1), meta["count"]) items := payload["payload"].([]any) require.Len(t, items, 1) item := items[0].(map[string]any) for _, key := range []string{"id", "call_id", "provider", "status", "direction", "duration_seconds", "conversation", "inbox", "agent", "contact", "transcript"} { require.Contains(t, item, key) } require.Equal(t, "in-progress", item["status"]) require.Equal(t, "inbound", item["direction"]) } func TestWhatsAppCallService_IndexScopesAgentsToHandledCalls(t *testing.T) { _, db, account, conversation := setupWhatsAppCallHandlerTest(t) agent := &model.User{Name: "Agent", Email: "call-agent@example.com"} require.NoError(t, db.Create(agent).Error) require.NoError(t, db.Create(&model.InboxMember{InboxID: conversation.InboxID, UserID: agent.ID}).Error) owned := &model.Call{AccountID: account.ID, InboxID: conversation.InboxID, ConversationID: conversation.ID, ContactID: conversation.ContactID, AcceptedByAgentID: &agent.ID, Provider: "whatsapp", Direction: "incoming", ProviderCallID: "owned", Status: "completed", CallerType: "Contact", CallerID: conversation.ContactID, CallDirection: "inbound"} other := &model.Call{AccountID: account.ID, InboxID: conversation.InboxID, ConversationID: conversation.ID, ContactID: conversation.ContactID, Provider: "whatsapp", Direction: "incoming", ProviderCallID: "other", Status: "completed", CallerType: "Contact", CallerID: conversation.ContactID, CallDirection: "inbound"} require.NoError(t, db.Create(owned).Error) require.NoError(t, db.Create(other).Error) svc := service.NewWhatsAppCallService(repository.NewWhatsAppCallRepo(db), fakeHandlerWhatsAppCallProvider{}) result, err := svc.ListAccountCalls(context.Background(), account.ID, service.AccountCallListFilter{UserID: agent.ID}) require.NoError(t, err) require.Equal(t, int64(1), result.Count) require.Len(t, result.Calls, 1) require.Equal(t, owned.ID, result.Calls[0].ID) } func TestWhatsAppCallService_IndexMatchesConversationAndReportManagerVisibility(t *testing.T) { _, db, account, conversation := setupWhatsAppCallHandlerTest(t) agent := &model.User{Name: "Agent", Email: "visibility@example.com"} require.NoError(t, db.Create(agent).Error) call := &model.Call{AccountID: account.ID, InboxID: conversation.InboxID, ConversationID: conversation.ID, ContactID: conversation.ContactID, AcceptedByAgentID: &agent.ID, Provider: "whatsapp", ProviderCallID: "visibility", Status: "completed"} require.NoError(t, db.Create(call).Error) svc := service.NewWhatsAppCallService(repository.NewWhatsAppCallRepo(db), fakeHandlerWhatsAppCallProvider{}) result, err := svc.ListAccountCalls(context.Background(), account.ID, service.AccountCallListFilter{UserID: agent.ID}) require.NoError(t, err) require.Zero(t, result.Count) require.NoError(t, db.Create(&model.InboxMember{InboxID: conversation.InboxID, UserID: agent.ID}).Error) result, err = svc.ListAccountCalls(context.Background(), account.ID, service.AccountCallListFilter{UserID: agent.ID}) require.NoError(t, err) require.Equal(t, int64(1), result.Count) role := &model.CustomRole{AccountID: account.ID, Name: "Report manager"} require.NoError(t, role.SetPermissionKeys([]model.PermissionDimension{model.DimensionReportManage})) require.NoError(t, db.Create(role).Error) require.NoError(t, db.Where("inbox_id = ? AND user_id = ?", conversation.InboxID, agent.ID).Delete(&model.InboxMember{}).Error) result, err = svc.ListAccountCalls(context.Background(), account.ID, service.AccountCallListFilter{UserID: agent.ID, CustomRoleID: role.ID}) require.NoError(t, err) require.Equal(t, int64(1), result.Count) } func TestWhatsAppCallHandler_AccountRoutesMatchFrontendAPI(t *testing.T) { router, db, account, conversation := setupWhatsAppCallHandlerTest(t) w := httptest.NewRecorder() body := []byte(`{"conversation_id":42,"sdp_offer":"sdp_offer"}`) req := httptest.NewRequest(http.MethodPost, "/api/v1/accounts/1/whatsapp_calls/initiate", bytes.NewReader(body)) req.Header.Set("Content-Type", "application/json") router.ServeHTTP(w, req) require.Equal(t, http.StatusOK, w.Code) resp := whatsappDecodeMap(t, w.Body.Bytes()) require.Equal(t, "calling", resp["status"]) require.Equal(t, "wacid_handler", resp["call_id"]) var call model.Call require.NoError(t, db.Where("account_id = ? AND conversation_id = ?", account.ID, conversation.ID).First(&call).Error) w = httptest.NewRecorder() req = httptest.NewRequest(http.MethodGet, "/api/v1/accounts/1/whatsapp_calls/"+whatsappItoaUint(call.ID), nil) router.ServeHTTP(w, req) require.Equal(t, http.StatusOK, w.Code) show := whatsappDecodeMap(t, w.Body.Bytes()) require.Equal(t, "wacid_handler", show["call_id"]) require.Equal(t, "whatsapp", show["provider"]) } func TestWhatsAppCallHandler_ActionsAndRecordingPayloads(t *testing.T) { router, db, account, conversation := setupWhatsAppCallHandlerTest(t) call := &model.Call{AccountID: account.ID, InboxID: 1, ConversationID: conversation.ID, ContactID: conversation.ContactID, Provider: "whatsapp", Direction: "incoming", ProviderCallID: "wacid_in", Status: "ringing", CallerType: "Contact", CallerID: conversation.ContactID, CallDirection: "inbound"} require.NoError(t, db.Create(call).Error) message := &model.Message{AccountID: account.ID, InboxID: 1, ConversationID: conversation.ID, ContentType: "voice_call", MessageType: "incoming"} require.NoError(t, db.Create(message).Error) require.NoError(t, db.Model(call).Update("message_id", message.ID).Error) w := httptest.NewRecorder() req := httptest.NewRequest(http.MethodPost, "/api/v1/accounts/1/whatsapp_calls/"+whatsappItoaUint(call.ID)+"/accept", bytes.NewReader([]byte(`{"sdp_answer":"sdp_answer"}`))) req.Header.Set("Content-Type", "application/json") router.ServeHTTP(w, req) require.Equal(t, http.StatusOK, w.Code) require.Equal(t, "in-progress", whatsappDecodeMap(t, w.Body.Bytes())["status"]) w = httptest.NewRecorder() req = httptest.NewRequest(http.MethodPost, "/api/v1/accounts/1/whatsapp_calls/"+whatsappItoaUint(call.ID)+"/terminate", nil) router.ServeHTTP(w, req) require.Equal(t, http.StatusOK, w.Code) require.Equal(t, "completed", whatsappDecodeMap(t, w.Body.Bytes())["status"]) var upload bytes.Buffer writer := multipart.NewWriter(&upload) part, err := writer.CreateFormFile("recording", "call.webm") require.NoError(t, err) _, err = part.Write([]byte("audio")) require.NoError(t, err) require.NoError(t, writer.Close()) w = httptest.NewRecorder() req = httptest.NewRequest(http.MethodPost, "/api/v1/accounts/1/whatsapp_calls/"+whatsappItoaUint(call.ID)+"/upload_recording", &upload) req.Header.Set("Content-Type", writer.FormDataContentType()) router.ServeHTTP(w, req) require.Equal(t, http.StatusOK, w.Code) require.Equal(t, "uploaded", whatsappDecodeMap(t, w.Body.Bytes())["status"]) } func whatsappDecodeMap(t *testing.T, body []byte) map[string]any { t.Helper() var out map[string]any require.NoError(t, json.Unmarshal(body, &out)) return out } func whatsappItoaUint(id uint) string { return strconv.FormatUint(uint64(id), 10) }