package config

import (
	"os"
	"testing"
)

func TestNewDefaultConfig(t *testing.T) {
	// Clear PORT env var for test
	oldPort := os.Getenv("PORT")
	os.Unsetenv("PORT")
	defer os.Setenv("PORT", oldPort)

	cfg := newDefaultConfig()
	if cfg.Port != 8080 {
		t.Errorf("expected default port 8080, got %d", cfg.Port)
	}
	expectedStateDir := getDefaultStateDir()
	if cfg.StateDir != expectedStateDir {
		t.Errorf("expected default state dir %s, got %s", expectedStateDir, cfg.StateDir)
	}
	if cfg.LogLevel != "info" {
		t.Errorf("expected default log level info, got %s", cfg.LogLevel)
	}
}

func TestGetPortFromEnv(t *testing.T) {
	tests := []struct {
		name     string
		envValue string
		expected int
	}{
		{"no env", "", 8080},
		{"valid port", "9090", 9090},
		{"invalid port", "invalid", 8080},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			oldPort := os.Getenv("PORT")
			if tt.envValue == "" {
				os.Unsetenv("PORT")
			} else {
				os.Setenv("PORT", tt.envValue)
			}
			defer os.Setenv("PORT", oldPort)

			port := getPortFromEnv()
			if port != tt.expected {
				t.Errorf("expected port %d, got %d", tt.expected, port)
			}
		})
	}
}

func TestNew(t *testing.T) {
	// Test with non-existent file (should use defaults)
	cfg, err := New("/nonexistent/config.yml")
	if err != nil {
		t.Fatalf("expected no error for non-existent file, got %v", err)
	}
	if cfg == nil {
		t.Fatal("expected config, got nil")
	}
}
