package http

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

	"github.com/codex-k8s/kodex/libs/go/errs"
	"github.com/labstack/echo/v5"
)

func TestResolvePathUnescaped_DecodesTemplateKeyFromEncodedURL(t *testing.T) {
	e := echo.New()
	req := httptest.NewRequest(http.MethodGet, "/api/v1/staff/resources/global%2Freviewer%2Fwork%2Fen/versions", nil)
	rec := httptest.NewRecorder()
	ctx := e.NewContext(req, rec)
	ctx.SetPath("/api/v1/staff/resources/:resource_key/versions")
	ctx.SetPathValues(echo.PathValues{{Name: "resource_key", Value: "global%2Freviewer%2Fwork%2Fen"}})

	got, err := resolvePathUnescaped("resource_key")(ctx)
	if err != nil {
		t.Fatalf("resolvePathUnescaped returned error: %v", err)
	}
	if got != "global/reviewer/work/en" {
		t.Fatalf("expected decoded resource key %q, got %q", "global/reviewer/work/en", got)
	}
}

func TestResolvePathUnescaped_ReturnsValidationErrorForInvalidEscape(t *testing.T) {
	e := echo.New()
	req := httptest.NewRequest(http.MethodGet, "/api/v1/staff/resources/template-key/versions", nil)
	rec := httptest.NewRecorder()
	ctx := e.NewContext(req, rec)
	ctx.SetPath("/api/v1/staff/resources/:resource_key/versions")
	ctx.SetPathValues(echo.PathValues{{Name: "resource_key", Value: "global%2Freviewer%2Fwork%2Fen%ZZ"}})

	_, err := resolvePathUnescaped("resource_key")(ctx)
	if err == nil {
		t.Fatal("expected validation error, got nil")
	}

	var validation errs.Validation
	if !errors.As(err, &validation) {
		t.Fatalf("expected errs.Validation, got %T", err)
	}
	if validation.Field != "resource_key" {
		t.Fatalf("expected validation field %q, got %q", "resource_key", validation.Field)
	}
}
