package response

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

	"github.com/labstack/echo/v4"
)

func TestNewPaginationDefaults(t *testing.T) {
	e := echo.New()
	req := httptest.NewRequest(http.MethodGet, "/?limit=10&offset=0&sort_by=created_at&sort_order=desc", nil)
	rec := httptest.NewRecorder()
	c := e.NewContext(req, rec)

	p, err := NewPagination(c)
	if err != nil {
		t.Fatalf("NewPagination: %v", err)
	}
	if p.Limit != 10 || p.Offset != 0 || p.Cursor != "" {
		t.Fatalf("unexpected pagination: %+v", p)
	}
}

func TestNewPaginationCursorConflict(t *testing.T) {
	e := echo.New()
	req := httptest.NewRequest(http.MethodGet, "/?limit=10&offset=5&cursor=abc", nil)
	rec := httptest.NewRecorder()
	c := e.NewContext(req, rec)

	_, err := NewPagination(c)
	if !IsPaginationError(err) {
		t.Fatalf("expected pagination conflict, got %v", err)
	}
}

func TestListMetaOmitsNextCursorOnLastPage(t *testing.T) {
	p := &Pagination{Limit: 10, Offset: 0}
	meta := p.ListMeta(15, "should-not-appear", false, 0)
	if meta.HasMore || meta.NextCursor != "" {
		t.Fatalf("expected no next cursor on last page: %+v", meta)
	}
	if meta.Page != 1 || meta.Pages != 2 || meta.Total != 15 {
		t.Fatalf("unexpected page meta: %+v", meta)
	}
}
