package track4

import (
	"net/http"
	"net/http/httptest"
	"os"
	"path/filepath"
	"testing"
)

func TestHandleValidatorsRejectsNonGET(t *testing.T) {
	server := NewServer(nil, 138)
	req := httptest.NewRequest(http.MethodPost, "/api/v1/track4/operator/validators", nil)
	w := httptest.NewRecorder()

	server.HandleValidators(w, req)

	if w.Code != http.StatusMethodNotAllowed {
		t.Fatalf("expected 405 for non-GET validators request, got %d", w.Code)
	}
}

func TestHandleContractsRequiresDatabase(t *testing.T) {
	server := NewServer(nil, 138)
	req := httptest.NewRequest(http.MethodGet, "/api/v1/track4/operator/contracts", nil)
	w := httptest.NewRecorder()

	server.HandleContracts(w, req)

	if w.Code != http.StatusServiceUnavailable {
		t.Fatalf("expected 503 when track4 DB is missing, got %d", w.Code)
	}
}

func TestLoadContractRegistryReadsConfiguredFile(t *testing.T) {
	tempDir := t.TempDir()
	registryPath := filepath.Join(tempDir, "smart-contracts-master.json")
	err := os.WriteFile(registryPath, []byte(`{
	  "chains": {
	    "138": {
	      "contracts": {
	        "CCIP_ROUTER": "0x1111111111111111111111111111111111111111",
	        "CHAIN138_BRIDGE": "0x2222222222222222222222222222222222222222"
	      }
	    }
	  }
	}`), 0o644)
	if err != nil {
		t.Fatalf("failed to write temp registry: %v", err)
	}

	t.Setenv("SMART_CONTRACTS_MASTER_JSON", registryPath)
	entries, err := loadContractRegistry(138)
	if err != nil {
		t.Fatalf("loadContractRegistry returned error: %v", err)
	}
	if len(entries) != 2 {
		t.Fatalf("expected 2 registry entries, got %d", len(entries))
	}
	if entries[0].Type == "" || entries[1].Type == "" {
		t.Fatal("expected contract types to be inferred")
	}
}
