package rest

import (
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"os"
	"strings"
	"testing"
)

func TestHandleWalletConnectConfig(t *testing.T) {
	t.Setenv("WALLETCONNECT_PROJECT_ID", "test-project-id")
	server := NewServer(nil, 138)

	req := httptest.NewRequest(http.MethodGet, "/api/v1/walletconnect/config", nil)
	rec := httptest.NewRecorder()
	server.handleWalletConnectConfig(rec, req)

	if rec.Code != http.StatusOK {
		t.Fatalf("expected 200, got %d", rec.Code)
	}

	var payload map[string]interface{}
	if err := json.Unmarshal(rec.Body.Bytes(), &payload); err != nil {
		t.Fatalf("decode response: %v", err)
	}
	if payload["projectId"] != "test-project-id" {
		t.Fatalf("expected project id, got %#v", payload["projectId"])
	}
	if payload["fallbackAuth"] != "/api/v1/auth/wallet" {
		t.Fatalf("expected fallback auth path, got %#v", payload["fallbackAuth"])
	}
}

func TestHandleWalletConnectConnectStub(t *testing.T) {
	server := NewServer(nil, 138)

	req := httptest.NewRequest(http.MethodPost, "/api/v1/walletconnect/connect", strings.NewReader("{}"))
	rec := httptest.NewRecorder()
	server.handleWalletConnectConnect(rec, req)

	if rec.Code != http.StatusNotImplemented {
		t.Fatalf("expected 501, got %d", rec.Code)
	}

	var payload map[string]interface{}
	if err := json.Unmarshal(rec.Body.Bytes(), &payload); err != nil {
		t.Fatalf("decode response: %v", err)
	}
	if payload["status"] != "stub" {
		t.Fatalf("expected stub status, got %#v", payload["status"])
	}
}

func TestHandleWalletConnectSessionStub(t *testing.T) {
	server := NewServer(nil, 138)

	req := httptest.NewRequest(http.MethodGet, "/api/v1/walletconnect/session/demo-session", nil)
	rec := httptest.NewRecorder()
	server.handleWalletConnectSession(rec, req)

	if rec.Code != http.StatusNotImplemented {
		t.Fatalf("expected 501, got %d", rec.Code)
	}
}

func TestHandleWalletConnectRootIndex(t *testing.T) {
	_ = os.Setenv("WALLETCONNECT_PROJECT_ID", "")
	server := NewServer(nil, 138)

	req := httptest.NewRequest(http.MethodGet, "/api/v1/walletconnect", nil)
	rec := httptest.NewRecorder()
	server.handleWalletConnectRoot(rec, req)

	if rec.Code != http.StatusOK {
		t.Fatalf("expected 200, got %d", rec.Code)
	}
}
