package config

import (
	"os"
	"path/filepath"
	"strings"
	"testing"
)

func TestDocumentPreservesUnknownKeysAndUpdatesHTTPPort(t *testing.T) {
	path := filepath.Join(t.TempDir(), "config.yaml")
	input := "# keep this comment\nserver:\n  http:\n    addr: 127.0.0.1:8000\ncustom:\n  enabled: true\n"
	if err := os.WriteFile(path, []byte(input), 0o600); err != nil {
		t.Fatal(err)
	}
	document, err := OpenDocument(path)
	if err != nil {
		t.Fatal(err)
	}
	if err = document.SetServerHTTPPort(9000); err != nil {
		t.Fatal(err)
	}
	if err = document.Set("admin", map[string]any{"router_prefix": "/api"}); err != nil {
		t.Fatal(err)
	}
	if err = document.Save(); err != nil {
		t.Fatal(err)
	}
	loaded, err := os.ReadFile(path)
	if err != nil {
		t.Fatal(err)
	}
	text := string(loaded)
	for _, want := range []string{"127.0.0.1:9000", "custom:", "enabled: true", "admin:", "router_prefix: /api"} {
		if !strings.Contains(text, want) {
			t.Fatalf("saved document missing %q:\n%s", want, text)
		}
	}
}
