package pgsql

import (
	"strings"
	"testing"
)

func TestBuildApplicationName_IncludesVersion(t *testing.T) {
	got := BuildApplicationName("")
	if !strings.HasPrefix(got, "relspecgo/") {
		t.Fatalf("BuildApplicationName() = %q, expected prefix relspecgo/", got)
	}
}

func TestBuildApplicationName_IncludesComponent(t *testing.T) {
	got := BuildApplicationName("reader-pgsql")
	if !strings.Contains(got, ":reader-pgsql") {
		t.Fatalf("BuildApplicationName(component) = %q, expected component suffix", got)
	}
}

func TestBuildApplicationName_RespectsPostgresLengthLimit(t *testing.T) {
	got := BuildApplicationName(strings.Repeat("x", 200))
	if len(got) > 63 {
		t.Fatalf("BuildApplicationName() length = %d, expected <= 63", len(got))
	}
}

func TestParseConfigWithApplicationName_AddsWhenMissing(t *testing.T) {
	cfg, err := ParseConfigWithApplicationName("postgres://user:pass@localhost:5432/db", "reader-pgsql")
	if err != nil {
		t.Fatalf("ParseConfigWithApplicationName() error = %v", err)
	}

	appName := cfg.RuntimeParams["application_name"]
	if appName == "" {
		t.Fatal("expected application_name to be set")
	}
	if !strings.HasPrefix(appName, "relspecgo/") {
		t.Fatalf("application_name = %q, expected relspecgo/<version> prefix", appName)
	}
}

func TestParseConfigWithApplicationName_PreservesExplicitValue(t *testing.T) {
	cfg, err := ParseConfigWithApplicationName("postgres://user:pass@localhost:5432/db?application_name=custom-app", "reader-pgsql")
	if err != nil {
		t.Fatalf("ParseConfigWithApplicationName() error = %v", err)
	}

	if got := cfg.RuntimeParams["application_name"]; got != "custom-app" {
		t.Fatalf("application_name = %q, expected %q", got, "custom-app")
	}
}
