package config

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

// stubStreamSecret keeps existing tests focused on the fields they
// assert against by short-circuiting the auto-generation path (which
// would otherwise write ./data/stream_secret in the test workspace).
// New tests that exercise the resolver directly do NOT use this.
func stubStreamSecret(t *testing.T) {
	t.Helper()
	t.Setenv("MINSTREL_STREAM_SECRET",
		base64.RawURLEncoding.EncodeToString([]byte("test-stream-secret-stub-1234567890")))
}

func TestDefault(t *testing.T) {
	cfg := Default()
	if cfg.Server.Address != ":4533" {
		t.Errorf("default server address = %q, want :4533", cfg.Server.Address)
	}
	if cfg.Log.Level != "info" {
		t.Errorf("default log level = %q, want info", cfg.Log.Level)
	}
}

func TestLoadYAML(t *testing.T) {
	stubStreamSecret(t)
	dir := t.TempDir()
	path := filepath.Join(dir, "config.yaml")
	content := []byte(`server:
  address: ":9000"
database:
  url: "postgres://example"
log:
  level: "debug"
  format: "json"
`)
	if err := os.WriteFile(path, content, 0o644); err != nil {
		t.Fatal(err)
	}
	cfg, err := Load(path)
	if err != nil {
		t.Fatalf("Load: %v", err)
	}
	if cfg.Server.Address != ":9000" {
		t.Errorf("server.address = %q", cfg.Server.Address)
	}
	if cfg.Database.URL != "postgres://example" {
		t.Errorf("database.url = %q", cfg.Database.URL)
	}
	if cfg.Log.Level != "debug" || cfg.Log.Format != "json" {
		t.Errorf("log = %+v", cfg.Log)
	}
}

func TestLoadMissingFileReturnsDefaults(t *testing.T) {
	stubStreamSecret(t)
	cfg, err := Load(filepath.Join(t.TempDir(), "does-not-exist.yaml"))
	if err != nil {
		t.Fatalf("Load: %v", err)
	}
	if cfg.Server.Address != ":4533" {
		t.Errorf("expected defaults, got %+v", cfg)
	}
}

func TestEnvOverrides(t *testing.T) {
	stubStreamSecret(t)
	t.Setenv("MINSTREL_SERVER_ADDRESS", ":8080")
	t.Setenv("MINSTREL_DATABASE_URL", "postgres://env")
	t.Setenv("MINSTREL_LOG_LEVEL", "WARN")
	t.Setenv("MINSTREL_LOG_FORMAT", "JSON")

	cfg, err := Load("")
	if err != nil {
		t.Fatalf("Load: %v", err)
	}
	if cfg.Server.Address != ":8080" {
		t.Errorf("server.address = %q", cfg.Server.Address)
	}
	if cfg.Database.URL != "postgres://env" {
		t.Errorf("database.url = %q", cfg.Database.URL)
	}
	if cfg.Log.Level != "warn" {
		t.Errorf("log.level = %q, want lowercased warn", cfg.Log.Level)
	}
	if cfg.Log.Format != "json" {
		t.Errorf("log.format = %q, want lowercased json", cfg.Log.Format)
	}
}

func TestLibraryEnvOverrides(t *testing.T) {
	stubStreamSecret(t)
	t.Setenv("MINSTREL_LIBRARY_SCAN_PATHS", "/music:/other::/third")
	// Default is true; set false so the override path is actually exercised.
	t.Setenv("MINSTREL_LIBRARY_SCAN_ON_STARTUP", "false")

	cfg, err := Load("")
	if err != nil {
		t.Fatalf("Load: %v", err)
	}
	want := []string{"/music", "/other", "/third"}
	if len(cfg.Library.ScanPaths) != len(want) {
		t.Fatalf("scan_paths = %v, want %v", cfg.Library.ScanPaths, want)
	}
	for i, p := range want {
		if cfg.Library.ScanPaths[i] != p {
			t.Errorf("scan_paths[%d] = %q, want %q", i, cfg.Library.ScanPaths[i], p)
		}
	}
	if cfg.Library.ScanOnStartup {
		t.Error("scan_on_startup = true, want false (env override of the true default)")
	}
}

func TestSubsonicEnvOverride(t *testing.T) {
	stubStreamSecret(t)
	t.Setenv("MINSTREL_SUBSONIC_ALLOW_PLAINTEXT_PASSWORD", "true")
	cfg, err := Load("")
	if err != nil {
		t.Fatalf("Load: %v", err)
	}
	if !cfg.Subsonic.AllowPlaintextPassword {
		t.Error("allow_plaintext_password = false, want true")
	}
}

func TestLibraryYAMLLoads(t *testing.T) {
	stubStreamSecret(t)
	dir := t.TempDir()
	path := filepath.Join(dir, "config.yaml")
	content := []byte(`library:
  scan_paths:
    - /srv/music
    - /mnt/archive
  scan_on_startup: true
`)
	if err := os.WriteFile(path, content, 0o644); err != nil {
		t.Fatal(err)
	}
	cfg, err := Load(path)
	if err != nil {
		t.Fatalf("Load: %v", err)
	}
	if len(cfg.Library.ScanPaths) != 2 || cfg.Library.ScanPaths[0] != "/srv/music" {
		t.Errorf("scan_paths = %v", cfg.Library.ScanPaths)
	}
	if !cfg.Library.ScanOnStartup {
		t.Error("scan_on_startup = false")
	}
}

func TestBrandingDefaults(t *testing.T) {
	cfg := Default()
	if cfg.Branding.AppName != "Minstrel" {
		t.Errorf("AppName: got %q, want %q", cfg.Branding.AppName, "Minstrel")
	}
	if cfg.Branding.Description == "" {
		t.Errorf("Description: empty after Default(); want default tagline")
	}
}

func TestBrandingYAMLOverride(t *testing.T) {
	stubStreamSecret(t)
	dir := t.TempDir()
	path := filepath.Join(dir, "config.yaml")
	content := []byte(`branding:
  app_name: "Family Jukebox"
  description: "Our home library."
`)
	if err := os.WriteFile(path, content, 0o644); err != nil {
		t.Fatal(err)
	}
	cfg, err := Load(path)
	if err != nil {
		t.Fatalf("Load: %v", err)
	}
	if cfg.Branding.AppName != "Family Jukebox" {
		t.Errorf("AppName: got %q", cfg.Branding.AppName)
	}
	if cfg.Branding.Description != "Our home library." {
		t.Errorf("Description: got %q", cfg.Branding.Description)
	}
}

func TestStreamSecret_EnvOverride(t *testing.T) {
	want := []byte("hello-stream-secret-from-env-32b")
	t.Setenv("MINSTREL_STREAM_SECRET", base64.RawURLEncoding.EncodeToString(want))
	t.Setenv("MINSTREL_STORAGE_DATA_DIR", t.TempDir())
	cfg, err := Load("")
	if err != nil {
		t.Fatalf("Load: %v", err)
	}
	if string(cfg.StreamSecret) != string(want) {
		t.Fatalf("StreamSecret mismatch: got %q want %q", cfg.StreamSecret, want)
	}
}

func TestStreamSecret_AutoGenPersistsToDataDir(t *testing.T) {
	_ = os.Unsetenv("MINSTREL_STREAM_SECRET")
	dataDir := t.TempDir()
	t.Setenv("MINSTREL_STORAGE_DATA_DIR", dataDir)

	cfg, err := Load("")
	if err != nil {
		t.Fatalf("Load: %v", err)
	}
	if len(cfg.StreamSecret) != streamSecretBytes {
		t.Fatalf("StreamSecret len = %d, want %d", len(cfg.StreamSecret), streamSecretBytes)
	}
	path := filepath.Join(dataDir, streamSecretFile)
	buf, err := os.ReadFile(path)
	if err != nil {
		t.Fatalf("expected persisted secret at %s: %v", path, err)
	}
	decoded, err := base64.RawURLEncoding.DecodeString(strings.TrimSpace(string(buf)))
	if err != nil {
		t.Fatalf("persisted secret is not raw-url-base64: %v", err)
	}
	if string(decoded) != string(cfg.StreamSecret) {
		t.Fatal("persisted file does not match returned secret")
	}
	info, err := os.Stat(path)
	if err != nil {
		t.Fatalf("stat: %v", err)
	}
	// 0600 — never let other users read the HMAC key.
	if perm := info.Mode().Perm(); perm != 0o600 {
		t.Fatalf("perm = %o, want 0600", perm)
	}
}

func TestStreamSecret_LoadsPersistedOnSecondBoot(t *testing.T) {
	_ = os.Unsetenv("MINSTREL_STREAM_SECRET")
	dataDir := t.TempDir()
	t.Setenv("MINSTREL_STORAGE_DATA_DIR", dataDir)

	first, err := Load("")
	if err != nil {
		t.Fatalf("Load #1: %v", err)
	}
	second, err := Load("")
	if err != nil {
		t.Fatalf("Load #2: %v", err)
	}
	if string(first.StreamSecret) != string(second.StreamSecret) {
		t.Fatal("second Load got a different secret — file fallback didn't fire")
	}
}

func TestStreamSecret_RejectsMalformedEnvValue(t *testing.T) {
	t.Setenv("MINSTREL_STREAM_SECRET", "not!base64!!!")
	t.Setenv("MINSTREL_STORAGE_DATA_DIR", t.TempDir())
	if _, err := Load(""); err == nil {
		t.Fatal("expected error on malformed MINSTREL_STREAM_SECRET")
	}
}

func TestBrandingEnvOverride(t *testing.T) {
	stubStreamSecret(t)
	t.Setenv("MINSTREL_BRANDING_APP_NAME", "Office Music")
	t.Setenv("MINSTREL_BRANDING_DESCRIPTION", "Office tunes.")
	cfg, err := Load("")
	if err != nil {
		t.Fatalf("Load: %v", err)
	}
	if cfg.Branding.AppName != "Office Music" {
		t.Errorf("AppName: got %q", cfg.Branding.AppName)
	}
	if cfg.Branding.Description != "Office tunes." {
		t.Errorf("Description: got %q", cfg.Branding.Description)
	}
}
