package integration

import (
	"io"
	"net/http"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

// ==============================================================================
// Approval & Process Route Tests
// Verifies that /process/approvals and /process/rules routes are correctly
// registered (not doubled as /process/approvals/approvals).
// ==============================================================================

func TestProcessAPI_ApprovalRoutes(t *testing.T) {
	if testing.Short() {
		t.Skip("Skipping integration test")
	}

	client := newHTTPClient(t)

	t.Run("POST_process_approvals_returns_non_404", func(t *testing.T) {
		// The route should be registered at /process/approvals, not /process/approvals/approvals.
		// We expect a 400 (missing request body) or 200, but NOT 404.
		resp, err := client.request("POST", "/services/data/v63.0/process/approvals", map[string]interface{}{})
		require.NoError(t, err)
		defer resp.Body.Close()

		assert.NotEqual(t, http.StatusNotFound, resp.StatusCode,
			"POST /process/approvals should be registered, not 404")
		t.Logf("POST /process/approvals status: %d", resp.StatusCode)
	})

	t.Run("GET_process_rules_returns_200", func(t *testing.T) {
		resp, err := client.request("GET", "/services/data/v63.0/process/rules", nil)
		require.NoError(t, err)
		defer resp.Body.Close()

		assert.Equal(t, http.StatusOK, resp.StatusCode,
			"GET /process/rules should return 200")

		body, _ := io.ReadAll(resp.Body)
		t.Logf("GET /process/rules response: %s", string(body)[:min(200, len(body))])
	})

	t.Run("Old_doubled_path_is_not_routed", func(t *testing.T) {
		// The old buggy path /process/approvals/approvals should NOT resolve to a
		// valid handler. It may return 404 (no route) or 403/401 (middleware rejects
		// before routing), but never 200 or 400 (which would mean a handler matched).
		resp, err := client.request("POST", "/services/data/v63.0/process/approvals/approvals", map[string]interface{}{})
		require.NoError(t, err)
		defer resp.Body.Close()

		assert.True(t, resp.StatusCode == http.StatusNotFound ||
			resp.StatusCode == http.StatusForbidden ||
			resp.StatusCode == http.StatusUnauthorized,
			"Old doubled path should not reach a handler, got %d", resp.StatusCode)
	})
}
