package infra

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

func TestHTTPCORSMiddleware(t *testing.T) {
	origins := []string{"https://example.com"}
	methods := []string{"GET", "POST"}

	base := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
	})

	t.Run("setea headers CORS en respuesta normal", func(t *testing.T) {
		mw := HTTPCORSMiddleware(origins, methods)
		handler := mw(base)

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

		if rec.Code != http.StatusOK {
			t.Errorf("got status %d, want 200", rec.Code)
		}
		if rec.Header().Get("Access-Control-Allow-Origin") == "" {
			t.Error("Access-Control-Allow-Origin header not set")
		}
	})

	t.Run("responde 204 a peticion OPTIONS preflight", func(t *testing.T) {
		mw := HTTPCORSMiddleware(origins, methods)
		handler := mw(base)

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

		if rec.Code != http.StatusNoContent {
			t.Errorf("got status %d, want 204", rec.Code)
		}
	})

	t.Run("headers incluyen los origenes configurados", func(t *testing.T) {
		mw := HTTPCORSMiddleware([]string{"https://app.example.com"}, methods)
		handler := mw(base)

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

		got := rec.Header().Get("Access-Control-Allow-Origin")
		if got != "https://app.example.com" {
			t.Errorf("got Access-Control-Allow-Origin=%q, want %q", got, "https://app.example.com")
		}
	})

	t.Run("headers incluyen los metodos configurados", func(t *testing.T) {
		mw := HTTPCORSMiddleware(origins, []string{"GET", "DELETE"})
		handler := mw(base)

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

		got := rec.Header().Get("Access-Control-Allow-Methods")
		if got != "GET, DELETE" {
			t.Errorf("got Access-Control-Allow-Methods=%q, want %q", got, "GET, DELETE")
		}
	})
}
