package middleware

import (
	"bytes"
	"encoding/json"
	"log/slog"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/stretchr/testify/require"
)

func TestLogger_LogsRequest(t *testing.T) {
	var buf bytes.Buffer
	log := slog.New(slog.NewJSONHandler(&buf, nil))

	chain := RequestID(Logger(log)(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		w.WriteHeader(http.StatusNoContent)
	})))

	rec := httptest.NewRecorder()
	chain.ServeHTTP(rec, httptest.NewRequest("GET", "/x", nil))

	var line map[string]any
	require.NoError(t, json.Unmarshal(buf.Bytes(), &line))
	require.Equal(t, "http", line["msg"])
	require.Equal(t, "/x", line["path"])
	require.Equal(t, "GET", line["method"])
	require.EqualValues(t, http.StatusNoContent, line["status"])
	require.NotEmpty(t, line["request_id"])
}

func TestLogger_DefaultStatus200(t *testing.T) {
	var buf bytes.Buffer
	log := slog.New(slog.NewJSONHandler(&buf, nil))

	h := Logger(log)(http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {
		// Handler writes nothing — status should default to 200.
	}))

	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, httptest.NewRequest("GET", "/y", nil))

	var line map[string]any
	require.NoError(t, json.Unmarshal(buf.Bytes(), &line))
	require.EqualValues(t, http.StatusOK, line["status"])
}
