package main

import (
	"encoding/json"
	"os"
	"path/filepath"
	"testing"
)

func TestDefaultConfigPort(t *testing.T) {
	cfg := DefaultConfig()
	if cfg.Port != 8989 {
		t.Fatalf("expected port 8989, got %d", cfg.Port)
	}
}

func TestLoadConfigFromFile(t *testing.T) {
	dir := t.TempDir()
	cfgPath := filepath.Join(dir, "config.json")
	data, err := json.Marshal(DefaultConfig())
	if err != nil {
		t.Fatal(err)
	}
	if err := os.WriteFile(cfgPath, data, 0644); err != nil {
		t.Fatal(err)
	}
	raw, err := os.ReadFile(cfgPath)
	if err != nil {
		t.Fatal(err)
	}
	var loaded Config
	if err := json.Unmarshal(raw, &loaded); err != nil {
		t.Fatal(err)
	}
	if loaded.Port != 8989 {
		t.Fatalf("expected port 8989, got %d", loaded.Port)
	}
}

func TestMergeConfigPreservesPoolTLSWhenPartialUpdate(t *testing.T) {
	dst := DefaultConfig()
	dst.Pool.UseTLS = true
	src := &Config{Port: 9000}
	mergeConfig(dst, src)
	if dst.Port != 9000 {
		t.Fatalf("port not merged")
	}
	// Known issue documented in PROBLEMS.md — bool zero-value overwrite
	if !dst.Pool.UseTLS {
		t.Log("NOTE: mergeConfig still resets UseTLS on partial PUT — tracked as H14")
	}
}

func TestConfigJSONRoundTrip(t *testing.T) {
	cfg := DefaultConfig()
	cfg.Wallet.Address = "48testwallet"
	data, err := json.Marshal(cfg)
	if err != nil {
		t.Fatal(err)
	}
	var decoded Config
	if err := json.Unmarshal(data, &decoded); err != nil {
		t.Fatal(err)
	}
	if decoded.Wallet.Address != cfg.Wallet.Address {
		t.Fatalf("wallet mismatch")
	}
}
