//go:build test

package mw

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

// TestJsonContentType_Middleware verifies that the JsonContentType middleware
// sets Content-Type: application/json on all responses.
func TestJsonContentType_Middleware(t *testing.T) {
	t.Parallel()

	// Create a simple handler that writes "ok"
	next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("ok"))
	})

	// Wrap with JsonContentType middleware
	handler := JsonContentType(next)

	req := httptest.NewRequest("GET", "/", nil)
	w := httptest.NewRecorder()

	handler.ServeHTTP(w, req)

	// Verify Content-Type is set
	ct := w.Header().Get("Content-Type")
	if ct != "application/json" {
		t.Errorf("expected Content-Type 'application/json', got %q", ct)
	}

	// Verify body is preserved
	if w.Body.String() != "ok" {
		t.Errorf("expected body 'ok', got %q", w.Body.String())
	}
}

// TestJsonContentType_HandlerCanOverride verifies that the downstream handler
// can override the Content-Type if needed.
func TestJsonContentType_HandlerCanOverride(t *testing.T) {
	t.Parallel()

	next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
		w.Write([]byte("override"))
	})

	handler := JsonContentType(next)

	req := httptest.NewRequest("GET", "/", nil)
	w := httptest.NewRecorder()

	handler.ServeHTTP(w, req)

	// The handler's Content-Type should win (it was set after middleware)
	ct := w.Header().Get("Content-Type")
	if ct != "text/plain; charset=utf-8" {
		t.Errorf("expected Content-Type 'text/plain; charset=utf-8', got %q", ct)
	}

	if w.Body.String() != "override" {
		t.Errorf("expected body 'override', got %q", w.Body.String())
	}
}

// TestJsonContentType_StatusOK verifies that the middleware passes through the
// handler's status code correctly.
func TestJsonContentType_StatusOK(t *testing.T) {
	t.Parallel()

	next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusCreated)
		w.Write([]byte(`{"id": "abc"}`))
	})

	handler := JsonContentType(next)

	req := httptest.NewRequest("POST", "/", nil)
	w := httptest.NewRecorder()

	handler.ServeHTTP(w, req)

	if w.Code != http.StatusCreated {
		t.Errorf("expected status 201, got %d", w.Code)
	}
	if w.Header().Get("Content-Type") != "application/json" {
		t.Errorf("expected Content-Type 'application/json', got %q", w.Header().Get("Content-Type"))
	}
	if w.Body.String() != `{"id": "abc"}` {
		t.Errorf("expected body `{\"id\": \"abc\"}`, got %q", w.Body.String())
	}
}
