package middleware

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

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

func TestOperationLogRecord_AllowsNilRepository(t *testing.T) {
	gin.SetMode(gin.TestMode)

	router := gin.New()
	router.Use((&OperationLogMiddleware{}).Record())
	router.POST("/operation-log", func(c *gin.Context) {
		c.JSON(http.StatusCreated, gin.H{"ok": true})
	})

	body := bytes.NewBufferString(`{"password":"secret","token":"abc"}`)
	req := httptest.NewRequest(http.MethodPost, "/operation-log", body)
	req.Header.Set("Content-Type", "application/json")
	recorder := httptest.NewRecorder()

	router.ServeHTTP(recorder, req)

	if recorder.Code != http.StatusCreated {
		t.Fatalf("unexpected status: got %d want %d", recorder.Code, http.StatusCreated)
	}
}

func TestSanitizeParams_MasksSensitiveFields(t *testing.T) {
	sanitized := sanitizeParams([]byte(`{"password":"secret","nested":"ok","token":"abc"}`))

	var payload map[string]any
	if err := json.Unmarshal([]byte(sanitized), &payload); err != nil {
		t.Fatalf("sanitized payload should remain valid json: %v", err)
	}
	if payload["password"] != "***" {
		t.Fatalf("password should be masked, got: %#v", payload["password"])
	}
	if payload["token"] != "***" {
		t.Fatalf("token should be masked, got: %#v", payload["token"])
	}
}

func TestSanitizeParams_FallbacksForNonJSONPayload(t *testing.T) {
	longText := strings.Repeat("x", 600)
	sanitized := sanitizeParams([]byte(longText))
	if len(sanitized) != 503 {
		t.Fatalf("expected truncated fallback length 503, got %d", len(sanitized))
	}
	if !strings.HasSuffix(sanitized, "...") {
		t.Fatalf("expected truncated fallback to end with ellipsis: %q", sanitized[len(sanitized)-3:])
	}
}
