package infra

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

func TestPushPromRemote(t *testing.T) {
	t.Run("body llega completo y status 204 es exito", func(t *testing.T) {
		const body = "node_load1 0.42 1700000000000\nnode_cpu_percent 3\n"
		var gotBody string
		srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			b, _ := io.ReadAll(r.Body)
			gotBody = string(b)
			if ct := r.Header.Get("Content-Type"); ct != "text/plain" {
				t.Errorf("Content-Type = %q, want text/plain", ct)
			}
			w.WriteHeader(http.StatusNoContent)
		}))
		defer srv.Close()

		if err := PushPromRemote(srv.URL, "", "", body, nil); err != nil {
			t.Fatalf("unexpected error: %v", err)
		}
		if gotBody != body {
			t.Errorf("body got %q, want %q", gotBody, body)
		}
	})

	t.Run("basic auth presente cuando user no vacio", func(t *testing.T) {
		var hadAuth bool
		var gotUser, gotPass string
		srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			gotUser, gotPass, hadAuth = r.BasicAuth()
			w.WriteHeader(http.StatusNoContent)
		}))
		defer srv.Close()

		if err := PushPromRemote(srv.URL, "alice", "s3cr3t", "x 1\n", nil); err != nil {
			t.Fatalf("unexpected error: %v", err)
		}
		if !hadAuth {
			t.Fatal("expected Authorization Basic header, got none")
		}
		if gotUser != "alice" || gotPass != "s3cr3t" {
			t.Errorf("basic auth = %q/%q, want alice/s3cr3t", gotUser, gotPass)
		}
	})

	t.Run("sin user no manda Authorization", func(t *testing.T) {
		var hadAuth bool
		srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			_, _, hadAuth = r.BasicAuth()
			w.WriteHeader(http.StatusNoContent)
		}))
		defer srv.Close()

		if err := PushPromRemote(srv.URL, "", "ignored", "x 1\n", nil); err != nil {
			t.Fatalf("unexpected error: %v", err)
		}
		if hadAuth {
			t.Error("expected no Authorization header when user is empty")
		}
	})

	t.Run("extra_label aparece en la query", func(t *testing.T) {
		var gotQuery []string
		srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			gotQuery = r.URL.Query()["extra_label"]
			w.WriteHeader(http.StatusNoContent)
		}))
		defer srv.Close()

		labels := map[string]string{"instance": "lucas", "region": "eu"}
		if err := PushPromRemote(srv.URL, "", "", "x 1\n", labels); err != nil {
			t.Fatalf("unexpected error: %v", err)
		}
		if len(gotQuery) != 2 {
			t.Fatalf("got %d extra_label params, want 2: %v", len(gotQuery), gotQuery)
		}
		joined := strings.Join(gotQuery, ",")
		if !strings.Contains(joined, "instance=lucas") {
			t.Errorf("extra_label missing instance=lucas: %v", gotQuery)
		}
		if !strings.Contains(joined, "region=eu") {
			t.Errorf("extra_label missing region=eu: %v", gotQuery)
		}
	})

	t.Run("status 500 produce error con codigo y snippet", func(t *testing.T) {
		srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			w.WriteHeader(http.StatusInternalServerError)
			io.WriteString(w, "boom: bad input")
		}))
		defer srv.Close()

		err := PushPromRemote(srv.URL, "", "", "x 1\n", nil)
		if err == nil {
			t.Fatal("expected error on status 500, got nil")
		}
		if !strings.Contains(err.Error(), "500") {
			t.Errorf("error should mention status 500: %v", err)
		}
		if !strings.Contains(err.Error(), "boom") {
			t.Errorf("error should include response body snippet: %v", err)
		}
	})
}
