package echohelpers

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

	"github.com/labstack/echo/v4"
	"github.com/stretchr/testify/assert"
)

func TestParsePagination(t *testing.T) {
	tests := []struct {
		name           string
		query          string
		maxLimit       int
		expectedLimit  int
		expectedOffset int
	}{
		{
			name:           "Defaults - no query params",
			query:          "/",
			maxLimit:       200,
			expectedLimit:  50,
			expectedOffset: 0,
		},
		{
			name:           "Custom values",
			query:          "/?limit=20&offset=10",
			maxLimit:       200,
			expectedLimit:  20,
			expectedOffset: 10,
		},
		{
			name:           "Max limit capped",
			query:          "/?limit=500",
			maxLimit:       200,
			expectedLimit:  200,
			expectedOffset: 0,
		},
		{
			name:           "Negative offset ignored",
			query:          "/?offset=-5",
			maxLimit:       200,
			expectedLimit:  50,
			expectedOffset: 0,
		},
		{
			name:           "Invalid limit falls back to default",
			query:          "/?limit=abc",
			maxLimit:       200,
			expectedLimit:  50,
			expectedOffset: 0,
		},
		{
			name:           "Zero limit falls back to default",
			query:          "/?limit=0",
			maxLimit:       200,
			expectedLimit:  50,
			expectedOffset: 0,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			e := echo.New()
			req := httptest.NewRequest(http.MethodGet, tt.query, nil)
			rec := httptest.NewRecorder()
			c := e.NewContext(req, rec)

			limit, offset := ParsePagination(c, tt.maxLimit)

			assert.Equal(t, tt.expectedLimit, limit, "limit mismatch")
			assert.Equal(t, tt.expectedOffset, offset, "offset mismatch")
		})
	}
}
