package core

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

func TestTestHTTPServer(t *testing.T) {
	t.Run("ruta registrada responde con el handler correcto", func(t *testing.T) {
		srv := TestHTTPServer(t, map[string]http.HandlerFunc{
			"/ping": func(w http.ResponseWriter, r *http.Request) {
				w.WriteHeader(http.StatusOK)
				_, _ = w.Write([]byte("pong"))
			},
		})

		resp, err := srv.Client.Get(srv.URL + "/ping")
		if err != nil {
			t.Fatalf("GET /ping: %v", err)
		}
		defer resp.Body.Close()

		if resp.StatusCode != http.StatusOK {
			t.Errorf("got status %d, want 200", resp.StatusCode)
		}

		body, _ := io.ReadAll(resp.Body)
		if string(body) != "pong" {
			t.Errorf("got body %q, want \"pong\"", string(body))
		}
	})

	t.Run("ruta no registrada devuelve 404", func(t *testing.T) {
		srv := TestHTTPServer(t, map[string]http.HandlerFunc{
			"/exists": func(w http.ResponseWriter, r *http.Request) {
				w.WriteHeader(http.StatusOK)
			},
		})

		resp, err := srv.Client.Get(srv.URL + "/notfound")
		if err != nil {
			t.Fatalf("GET /notfound: %v", err)
		}
		defer resp.Body.Close()

		if resp.StatusCode != http.StatusNotFound {
			t.Errorf("got status %d, want 404", resp.StatusCode)
		}
	})

	t.Run("multiples rutas independientes", func(t *testing.T) {
		srv := TestHTTPServer(t, map[string]http.HandlerFunc{
			"/a": func(w http.ResponseWriter, r *http.Request) {
				w.WriteHeader(http.StatusOK)
				_, _ = w.Write([]byte("route-a"))
			},
			"/b": func(w http.ResponseWriter, r *http.Request) {
				w.WriteHeader(http.StatusCreated)
				_, _ = w.Write([]byte("route-b"))
			},
		})

		respA, err := srv.Client.Get(srv.URL + "/a")
		if err != nil {
			t.Fatalf("GET /a: %v", err)
		}
		defer respA.Body.Close()
		if respA.StatusCode != http.StatusOK {
			t.Errorf("/a: got status %d, want 200", respA.StatusCode)
		}

		respB, err := srv.Client.Get(srv.URL + "/b")
		if err != nil {
			t.Fatalf("GET /b: %v", err)
		}
		defer respB.Body.Close()
		if respB.StatusCode != http.StatusCreated {
			t.Errorf("/b: got status %d, want 201", respB.StatusCode)
		}
	})
}
