package infra

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

func TestHTTPMiddlewareChain(t *testing.T) {
	t.Run("sin middlewares pasa al handler final", func(t *testing.T) {
		chain := HTTPMiddlewareChain()
		handler := chain(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			w.WriteHeader(http.StatusOK)
			w.Write([]byte("final"))
		}))

		rec := httptest.NewRecorder()
		req := httptest.NewRequest("GET", "/", nil)
		handler.ServeHTTP(rec, req)

		if rec.Code != http.StatusOK {
			t.Errorf("got status %d, want %d", rec.Code, http.StatusOK)
		}
		if rec.Body.String() != "final" {
			t.Errorf("got body %q, want %q", rec.Body.String(), "final")
		}
	})

	t.Run("un middleware se aplica correctamente", func(t *testing.T) {
		addHeader := func(next http.Handler) http.Handler {
			return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
				w.Header().Set("X-Test", "applied")
				next.ServeHTTP(w, r)
			})
		}

		chain := HTTPMiddlewareChain(Middleware(addHeader))
		handler := chain(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			w.WriteHeader(http.StatusOK)
		}))

		rec := httptest.NewRecorder()
		req := httptest.NewRequest("GET", "/", nil)
		handler.ServeHTTP(rec, req)

		if rec.Header().Get("X-Test") != "applied" {
			t.Errorf("got X-Test=%q, want %q", rec.Header().Get("X-Test"), "applied")
		}
	})

	t.Run("dos middlewares se aplican en orden izquierda-derecha", func(t *testing.T) {
		order := []string{}

		first := Middleware(func(next http.Handler) http.Handler {
			return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
				order = append(order, "first")
				next.ServeHTTP(w, r)
			})
		})
		second := Middleware(func(next http.Handler) http.Handler {
			return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
				order = append(order, "second")
				next.ServeHTTP(w, r)
			})
		})

		chain := HTTPMiddlewareChain(first, second)
		handler := chain(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			order = append(order, "handler")
			w.WriteHeader(http.StatusOK)
		}))

		rec := httptest.NewRecorder()
		req := httptest.NewRequest("GET", "/", nil)
		handler.ServeHTTP(rec, req)

		if len(order) != 3 || order[0] != "first" || order[1] != "second" || order[2] != "handler" {
			t.Errorf("got order %v, want [first second handler]", order)
		}
	})
}
