package config

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

func TestLoadDefaults(t *testing.T) {
	cfg, err := Load("/nonexistent/config.toml")
	if err != nil {
		t.Fatalf("Load with missing file should return defaults: %v", err)
	}
	if cfg.Server.Port != 8080 {
		t.Errorf("expected default port 8080, got %d", cfg.Server.Port)
	}
	if len(cfg.Engines.LocalPorted) != 5 {
		t.Errorf("expected 5 default engines, got %d", len(cfg.Engines.LocalPorted))
	}
}

func TestLoadFromFile(t *testing.T) {
	// Clear env vars so we test pure config file values
	t.Setenv("PORT", "")
	t.Setenv("HTTP_TIMEOUT", "")
	t.Setenv("UPSTREAM_SEARXNG_URL", "")
	t.Setenv("LOCAL_PORTED_ENGINES", "")
	t.Setenv("BRAVE_API_KEY", "")
	t.Setenv("BRAVE_ACCESS_TOKEN", "")

	dir := t.TempDir()
	path := filepath.Join(dir, "config.toml")
	content := `
[server]
port = 9090
http_timeout = "30s"

[upstream]
url = "http://localhost:8888"

[engines]
local_ported = ["wikipedia", "braveapi"]

[engines.brave]
api_key = "test-key"
access_token = "secret"

[engines.qwant]
category = "web"
results_per_page = 5
`
	if err := os.WriteFile(path, []byte(content), 0644); err != nil {
		t.Fatal(err)
	}

	cfg, err := Load(path)
	if err != nil {
		t.Fatalf("Load failed: %v", err)
	}

	if cfg.Server.Port != 9090 {
		t.Errorf("expected port 9090, got %d", cfg.Server.Port)
	}
	if cfg.Server.HTTPTimeout != "30s" {
		t.Errorf("expected http_timeout 30s, got %s", cfg.Server.HTTPTimeout)
	}
	if cfg.Upstream.URL != "http://localhost:8888" {
		t.Errorf("expected upstream URL, got %s", cfg.Upstream.URL)
	}
	if len(cfg.Engines.LocalPorted) != 2 {
		t.Errorf("expected 2 engines, got %d", len(cfg.Engines.LocalPorted))
	}
	if cfg.Engines.Brave.APIKey != "test-key" {
		t.Errorf("expected brave api_key, got %s", cfg.Engines.Brave.APIKey)
	}
	if cfg.Engines.Brave.AccessToken != "secret" {
		t.Errorf("expected brave access_token, got %s", cfg.Engines.Brave.AccessToken)
	}
	if cfg.Engines.Qwant.Category != "web" {
		t.Errorf("expected qwant category web, got %s", cfg.Engines.Qwant.Category)
	}
	if cfg.Engines.Qwant.ResultsPerPage != 5 {
		t.Errorf("expected qwant results_per_page 5, got %d", cfg.Engines.Qwant.ResultsPerPage)
	}
}

func TestEnvOverrides(t *testing.T) {
	t.Setenv("PORT", "3000")
	t.Setenv("HTTP_TIMEOUT", "5s")
	t.Setenv("UPSTREAM_SEARXNG_URL", "http://env:9999")
	t.Setenv("BRAVE_API_KEY", "env-key")
	t.Setenv("LOCAL_PORTED_ENGINES", "wikipedia,arxiv")

	cfg, err := Load("/nonexistent/config.toml")
	if err != nil {
		t.Fatal(err)
	}

	if cfg.Server.Port != 3000 {
		t.Errorf("expected env port 3000, got %d", cfg.Server.Port)
	}
	if cfg.Server.HTTPTimeout != "5s" {
		t.Errorf("expected env timeout 5s, got %s", cfg.Server.HTTPTimeout)
	}
	if cfg.Upstream.URL != "http://env:9999" {
		t.Errorf("expected env upstream URL, got %s", cfg.Upstream.URL)
	}
	if cfg.Engines.Brave.APIKey != "env-key" {
		t.Errorf("expected env brave key, got %s", cfg.Engines.Brave.APIKey)
	}
	if len(cfg.Engines.LocalPorted) != 2 {
		t.Errorf("expected 2 env engines, got %d", len(cfg.Engines.LocalPorted))
	}
}

func TestConfigFileWinsOverDefaults(t *testing.T) {
	dir := t.TempDir()
	path := filepath.Join(dir, "config.toml")
	content := `
[server]
port = 7070
`
	if err := os.WriteFile(path, []byte(content), 0644); err != nil {
		t.Fatal(err)
	}

	t.Setenv("PORT", "3000") // env should override config

	cfg, err := Load(path)
	if err != nil {
		t.Fatal(err)
	}

	// Env overrides the config file
	if cfg.Server.Port != 3000 {
		t.Errorf("env should override config: expected 3000, got %d", cfg.Server.Port)
	}
}

func TestHTTPTimeout(t *testing.T) {
	cfg := &Config{Server: ServerConfig{HTTPTimeout: "5s"}}
	if d := cfg.HTTPTimeout(); d.String() != "5s" {
		t.Errorf("expected 5s, got %s", d)
	}

	// Invalid falls back to 10s
	cfg.Server.HTTPTimeout = "not-a-duration"
	if d := cfg.HTTPTimeout(); d.String() != "10s" {
		t.Errorf("expected fallback 10s, got %s", d)
	}
}
