package rest_test

import (
	"bytes"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/gin-gonic/gin"
	"github.com/nexuscrm/backend/internal/interfaces/rest"
	"github.com/nexuscrm/backend/pkg/auth"
	"github.com/nexuscrm/shared/pkg/constants"
	"github.com/stretchr/testify/assert"
)

// ---------------------------------------------------------------------------
// ActionHandler.CreateAction — validation
// ---------------------------------------------------------------------------

func TestActionHandler_CreateAction_InvalidJSON(t *testing.T) {
	w := httptest.NewRecorder()
	c, _ := gin.CreateTestContext(w)
	c.Request = httptest.NewRequest("POST", "/tooling/sobjects/QuickActionDefinition", bytes.NewReader([]byte(`{invalid`)))
	c.Request.Header.Set("Content-Type", "application/json")
	// Add a mock user to context to bypass authentication
	c.Set(constants.ContextKeyUser, auth.UserSession{
		ID:    "test-user-id",
		Name:  "Test User",
		Email: "test@example.com",
	})

	handler := rest.NewActionHandler(nil)
	handler.CreateAction(c)

	assert.Equal(t, http.StatusBadRequest, w.Code)
}

func TestActionHandler_CreateAction_Unauthenticated(t *testing.T) {
	w := httptest.NewRecorder()
	c, _ := gin.CreateTestContext(w)
	c.Request = httptest.NewRequest("POST", "/tooling/sobjects/QuickActionDefinition", bytes.NewReader([]byte(`{}`)))
	c.Request.Header.Set("Content-Type", "application/json")

	handler := rest.NewActionHandler(nil)
	assert.Panics(t, func() { handler.CreateAction(c) })
}
