package healthcheck

import (
	"context"
	"encoding/json"
	"net"
	"net/http"
	"net/http/httptest"
	"testing"
	"time"

	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
)

func TestHTTPHealthLiveAndReady(t *testing.T) {
	conn := startRoomGRPC(t)
	state := NewState("gateway-node-test", "jwt-secret", conn)
	state.MarkHTTPServing()
	waitReady(t, state)

	handler := NewHTTPHandler(state)

	liveRecorder := httptest.NewRecorder()
	handler.Live(liveRecorder, httptest.NewRequest(http.MethodGet, "/healthz/live", nil))
	if liveRecorder.Code != http.StatusOK {
		t.Fatalf("live status mismatch: got %d want %d body=%s", liveRecorder.Code, http.StatusOK, liveRecorder.Body.String())
	}

	var live Response
	if err := json.NewDecoder(liveRecorder.Body).Decode(&live); err != nil {
		t.Fatalf("decode live response failed: %v", err)
	}
	if live.Status != "ok" || live.Service != "gateway-service" || live.NodeID != "gateway-node-test" {
		t.Fatalf("unexpected live response: %+v", live)
	}

	readyRecorder := httptest.NewRecorder()
	handler.Ready(readyRecorder, httptest.NewRequest(http.MethodGet, "/healthz/ready", nil))
	if readyRecorder.Code != http.StatusOK {
		t.Fatalf("ready status mismatch: got %d want %d body=%s", readyRecorder.Code, http.StatusOK, readyRecorder.Body.String())
	}

	state.MarkDraining()
	drainingRecorder := httptest.NewRecorder()
	handler.Ready(drainingRecorder, httptest.NewRequest(http.MethodGet, "/healthz/ready", nil))
	if drainingRecorder.Code != http.StatusServiceUnavailable {
		t.Fatalf("draining ready status mismatch: got %d want %d body=%s", drainingRecorder.Code, http.StatusServiceUnavailable, drainingRecorder.Body.String())
	}
}

func TestReadyFailsWithoutJWTSecret(t *testing.T) {
	conn := startRoomGRPC(t)
	state := NewState("gateway-node-test", "", conn)
	state.MarkHTTPServing()

	handler := NewHTTPHandler(state)
	recorder := httptest.NewRecorder()
	handler.Ready(recorder, httptest.NewRequest(http.MethodGet, "/healthz/ready", nil))
	if recorder.Code != http.StatusServiceUnavailable {
		t.Fatalf("empty JWT ready status mismatch: got %d want %d body=%s", recorder.Code, http.StatusServiceUnavailable, recorder.Body.String())
	}

	var response Response
	if err := json.NewDecoder(recorder.Body).Decode(&response); err != nil {
		t.Fatalf("decode empty JWT response failed: %v", err)
	}
	if response.Status != "fail" || len(response.Checks) == 0 {
		t.Fatalf("ready failure should expose checks: %+v", response)
	}
}

func startRoomGRPC(t *testing.T) *grpc.ClientConn {
	t.Helper()

	listener, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		t.Fatalf("listen fake room gRPC failed: %v", err)
	}

	server := grpc.NewServer()
	go func() {
		_ = server.Serve(listener)
	}()

	conn, err := grpc.Dial(listener.Addr().String(), grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		t.Fatalf("dial fake room gRPC failed: %v", err)
	}

	t.Cleanup(func() {
		_ = conn.Close()
		server.Stop()
		_ = listener.Close()
	})

	return conn
}

func waitReady(t *testing.T, state *State) {
	t.Helper()

	deadline := time.Now().Add(2 * time.Second)
	for time.Now().Before(deadline) {
		if Healthy(state.Ready(context.Background())) {
			return
		}

		time.Sleep(10 * time.Millisecond)
	}

	t.Fatalf("state did not become ready before deadline: %+v", state.Ready(context.Background()))
}
