package track1

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

	"github.com/stretchr/testify/require"
)

func TestHandleMissionControlStreamSendsInitialEvent(t *testing.T) {
	rpc := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		var req struct {
			Method string `json:"method"`
		}
		require.NoError(t, json.NewDecoder(r.Body).Decode(&req))

		w.Header().Set("Content-Type", "application/json")
		switch req.Method {
		case "eth_blockNumber":
			_, _ = w.Write([]byte(`{"jsonrpc":"2.0","id":1,"result":"0x10"}`))
		case "eth_getBlockByNumber":
			ts := strconv.FormatInt(time.Now().Add(-2*time.Second).Unix(), 16)
			_, _ = w.Write([]byte(`{"jsonrpc":"2.0","id":1,"result":{"timestamp":"0x` + ts + `"}}`))
		default:
			http.Error(w, `{"jsonrpc":"2.0","id":1,"error":{"message":"unsupported"}}`, http.StatusBadRequest)
		}
	}))
	defer rpc.Close()

	t.Setenv("RPC_URL", rpc.URL)
	t.Setenv("ETH_MAINNET_RPC_URL", "")
	t.Setenv("MISSION_CONTROL_EXTRA_RPCS", "")
	t.Setenv("MISSION_CONTROL_VERIFY_JSON", "")
	t.Setenv("CCIP_RELAY_HEALTH_URL", "")
	t.Setenv("CCIP_RELAY_HEALTH_URLS", "")
	t.Setenv("MISSION_CONTROL_CCIP_JSON", "")

	s := &Server{}
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	req := httptest.NewRequest(http.MethodGet, "/api/v1/mission-control/stream", nil).WithContext(ctx)
	w := httptest.NewRecorder()

	done := make(chan struct{})
	go func() {
		s.HandleMissionControlStream(w, req)
		close(done)
	}()

	deadline := time.Now().Add(500 * time.Millisecond)
	for time.Now().Before(deadline) {
		if strings.Contains(w.Body.String(), "event: mission-control") {
			break
		}
		time.Sleep(10 * time.Millisecond)
	}

	cancel()
	<-done

	require.Contains(t, w.Header().Get("Content-Type"), "text/event-stream")
	require.Contains(t, w.Body.String(), "event: mission-control")
	require.Contains(t, w.Body.String(), `"status":"operational"`)
	require.Contains(t, w.Body.String(), `"chain-138"`)
}
