//go:build crm

package crm

import (
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/gin-gonic/gin"
)

const expectedSalesforceGeneric500 = `[{"errorCode":"INTERNAL_ERROR","message":"An internal server error occurred. Contact your system administrator."}]`

// salesforceInternalErrorProjector projects the Salesforce v63 generic-500 across the
// whole Salesforce data-API route family — INCLUDING the bare /services/data discovery
// root (the case that must not regress to the neutral L0 envelope).
func TestSalesforceInternalErrorProjector_SalesforceRoutes(t *testing.T) {
	gin.SetMode(gin.TestMode)
	for _, path := range []string{
		"/services/data",                        // bare discovery root
		"/services/data/",                       // trailing slash
		"/services/data/v63.0/sobjects/Account", // versioned tree
	} {
		t.Run(path, func(t *testing.T) {
			c, _ := gin.CreateTestContext(httptest.NewRecorder())
			c.Request = httptest.NewRequest(http.MethodGet, path, nil)
			status, body := salesforceInternalErrorProjector(c)
			if status != http.StatusInternalServerError {
				t.Fatalf("status = %d; want %d", status, http.StatusInternalServerError)
			}
			got, err := json.Marshal(body)
			if err != nil {
				t.Fatalf("marshal: %v", err)
			}
			if string(got) != expectedSalesforceGeneric500 {
				t.Fatalf("SF generic-500 body mismatch\n got: %s\nwant: %s", got, expectedSalesforceGeneric500)
			}
		})
	}
}

// A non-Salesforce (legacy/product) route gets the neutral L0 default, not SF skin.
func TestSalesforceInternalErrorProjector_NonSalesforceRouteIsNeutral(t *testing.T) {
	gin.SetMode(gin.TestMode)
	c, _ := gin.CreateTestContext(httptest.NewRecorder())
	c.Request = httptest.NewRequest(http.MethodGet, "/product/notification-reads/123", nil)

	status, body := salesforceInternalErrorProjector(c)
	if status != 0 || body != nil {
		t.Fatalf("non-Salesforce route must be neutral (0, nil); got (%d, %v)", status, body)
	}
}
