package v1 import ( "fmt" "net/http" "net/http/httptest" "testing" "github.com/gin-gonic/gin" "github.com/gochat/gochat/internal/csat" "github.com/gochat/gochat/internal/model" "github.com/gochat/gochat/internal/service" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" "gorm.io/driver/sqlite" "gorm.io/gorm" "gorm.io/gorm/logger" ) type csatDBProvider struct { db *gorm.DB } func (p *csatDBProvider) DB() *gorm.DB { return p.db } type CsatMetricsHandlerTestSuite struct { suite.Suite db *gorm.DB handler *CsatMetricsHandler account *model.Account } func (s *CsatMetricsHandlerTestSuite) SetupSuite() { gin.SetMode(gin.TestMode) db, err := gorm.Open(sqlite.Open("file::memory:"), &gorm.Config{ Logger: logger.Default.LogMode(logger.Silent), }) s.Require().NoError(err) s.Require().NoError(db.AutoMigrate(&model.Account{}, &csat.CsatSurveyResponse{}, &model.ReportingEventsRollup{}, &model.Conversation{})) s.db = db provider := &csatDBProvider{db: db} svc := service.NewCsatMetricsService(provider) s.handler = NewCsatMetricsHandler(svc) s.account = &model.Account{Name: "test-csat-account"} s.Require().NoError(db.Create(s.account).Error) } func (s *CsatMetricsHandlerTestSuite) TearDownSuite() { if s.db != nil { sqlDB, _ := s.db.DB() sqlDB.Close() } } func TestCsatMetricsHandlerSuite(t *testing.T) { suite.Run(t, new(CsatMetricsHandlerTestSuite)) } func (s *CsatMetricsHandlerTestSuite) TestMetrics_Success() { r := gin.New() r.GET("/api/v1/accounts/:account_id/csat_metrics", func(c *gin.Context) { c.Set("account_id", float64(s.account.ID)) s.handler.Metrics(c) }) w := httptest.NewRecorder() req, _ := http.NewRequest("GET", fmt.Sprintf("/api/v1/accounts/%d/csat_metrics", s.account.ID), nil) r.ServeHTTP(w, req) assert.Equal(s.T(), http.StatusOK, w.Code) } func (s *CsatMetricsHandlerTestSuite) TestDownload_Success() { r := gin.New() r.GET("/api/v1/accounts/:account_id/csat_metrics/download", func(c *gin.Context) { c.Set("account_id", float64(s.account.ID)) s.handler.Download(c) }) w := httptest.NewRecorder() req, _ := http.NewRequest("GET", fmt.Sprintf("/api/v1/accounts/%d/csat_metrics/download", s.account.ID), nil) r.ServeHTTP(w, req) // Download may return 200 with CSV or 404 if no data assert.True(s.T(), w.Code == http.StatusOK || w.Code == http.StatusNotFound || w.Code == http.StatusNoContent) }