package middleware

import (
	"bytes"
	"log/slog"
	"net"
	"net/http"
	"net/http/httptest"
	"os"
	"strings"
	"syscall"
	"testing"

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

func TestRecoveryRedactsCredentialsFromRequestDump(t *testing.T) {
	gin.SetMode(gin.TestMode)
	var output bytes.Buffer
	logger := slog.New(slog.NewTextHandler(&output, nil))
	engine := gin.New()
	engine.Use(Recovery(logger))
	engine.GET("/panic", func(*gin.Context) { panic("boom") })

	request := httptest.NewRequest(http.MethodGet, "/panic?token=query-secret&room=orders", nil)
	request.Header.Set("Authorization", "Bearer header-secret")
	request.Header.Set("Cookie", "x-token=cookie-secret")
	request.Header.Set("X-Trace-Id", "trace-id")
	response := httptest.NewRecorder()
	engine.ServeHTTP(response, request)

	if response.Code != http.StatusInternalServerError {
		t.Fatalf("status=%d, want %d", response.Code, http.StatusInternalServerError)
	}
	logText := output.String()
	for _, secret := range []string{"query-secret", "header-secret", "cookie-secret"} {
		if strings.Contains(logText, secret) {
			t.Fatalf("recovery log leaked %q: %s", secret, logText)
		}
	}
	if !strings.Contains(logText, "token=%2A%2A%2A") || !strings.Contains(logText, "Authorization: ***") || !strings.Contains(logText, "Cookie: ***") {
		t.Fatalf("recovery log did not contain expected redaction: %s", logText)
	}
}

func TestRecoveryDetectsWrappedBrokenPipe(t *testing.T) {
	pipe := &net.OpError{Op: "write", Net: "tcp", Err: os.NewSyscallError("write", syscall.EPIPE)}
	if !isBrokenPipe(wrappedBrokenPipeError{cause: pipe}) {
		t.Fatal("wrapped broken-pipe error was not detected")
	}
}

type wrappedBrokenPipeError struct{ cause error }

func (wrappedBrokenPipeError) Error() string   { return "wrapped broken pipe" }
func (e wrappedBrokenPipeError) Unwrap() error { return e.cause }
