package config

import (
	"testing"
	"time"

	"scrabble/backend/internal/postgres"
	"scrabble/backend/internal/telemetry"
)

// testDSN is a syntactically valid DSN used to satisfy the required-DSN check.
const testDSN = "postgres://u:p@localhost:5432/db?search_path=backend&sslmode=disable"

// TestLoadDefaults verifies that Load applies defaults when only the required
// DSN is set.
func TestLoadDefaults(t *testing.T) {
	t.Setenv("BACKEND_HTTP_ADDR", "")
	t.Setenv("BACKEND_LOG_LEVEL", "")
	t.Setenv("BACKEND_POSTGRES_DSN", testDSN)
	t.Setenv("BACKEND_DICT_DIR", "/dict")
	t.Setenv("BACKEND_DICT_VERSION", "")
	t.Setenv("BACKEND_GAME_TIMEOUT_SWEEP_INTERVAL", "")
	t.Setenv("BACKEND_GAME_CACHE_TTL", "")

	c, err := Load()
	if err != nil {
		t.Fatalf("Load: %v", err)
	}
	if c.HTTPAddr != defaultHTTPAddr {
		t.Errorf("HTTPAddr = %q, want %q", c.HTTPAddr, defaultHTTPAddr)
	}
	if c.LogLevel != defaultLogLevel {
		t.Errorf("LogLevel = %q, want %q", c.LogLevel, defaultLogLevel)
	}
	if c.Postgres.DSN != testDSN {
		t.Errorf("Postgres.DSN = %q, want %q", c.Postgres.DSN, testDSN)
	}
	if c.Postgres.MaxOpenConns != postgres.DefaultMaxOpenConns {
		t.Errorf("Postgres.MaxOpenConns = %d, want %d", c.Postgres.MaxOpenConns, postgres.DefaultMaxOpenConns)
	}
	if c.Telemetry.ServiceName != telemetry.DefaultServiceName {
		t.Errorf("Telemetry.ServiceName = %q, want %q", c.Telemetry.ServiceName, telemetry.DefaultServiceName)
	}
	if c.Telemetry.TracesExporter != telemetry.ExporterNone {
		t.Errorf("Telemetry.TracesExporter = %q, want %q", c.Telemetry.TracesExporter, telemetry.ExporterNone)
	}
	if c.Game.DictDir != "/dict" {
		t.Errorf("Game.DictDir = %q, want /dict", c.Game.DictDir)
	}
	if c.Game.DictVersion != "v1" {
		t.Errorf("Game.DictVersion = %q, want v1", c.Game.DictVersion)
	}
	if c.Game.TimeoutSweepInterval != time.Minute {
		t.Errorf("Game.TimeoutSweepInterval = %s, want 1m", c.Game.TimeoutSweepInterval)
	}
	if c.Game.CacheTTL != 24*time.Hour {
		t.Errorf("Game.CacheTTL = %s, want 24h", c.Game.CacheTTL)
	}
}

// TestLoadOverrides verifies that environment variables override the defaults.
func TestLoadOverrides(t *testing.T) {
	t.Setenv("BACKEND_POSTGRES_DSN", testDSN)
	t.Setenv("BACKEND_HTTP_ADDR", "127.0.0.1:9090")
	t.Setenv("BACKEND_LOG_LEVEL", "debug")
	t.Setenv("BACKEND_POSTGRES_MAX_OPEN_CONNS", "7")
	t.Setenv("BACKEND_POSTGRES_OPERATION_TIMEOUT", "3s")
	t.Setenv("BACKEND_SERVICE_NAME", "scrabble-test")
	t.Setenv("BACKEND_OTEL_TRACES_EXPORTER", "stdout")
	t.Setenv("BACKEND_DICT_DIR", "/srv/dict")
	t.Setenv("BACKEND_DICT_VERSION", "2026-06")
	t.Setenv("BACKEND_GAME_TIMEOUT_SWEEP_INTERVAL", "30s")
	t.Setenv("BACKEND_GAME_CACHE_TTL", "1h")

	c, err := Load()
	if err != nil {
		t.Fatalf("Load: %v", err)
	}
	if c.HTTPAddr != "127.0.0.1:9090" {
		t.Errorf("HTTPAddr = %q, want %q", c.HTTPAddr, "127.0.0.1:9090")
	}
	if c.Game.DictDir != "/srv/dict" || c.Game.DictVersion != "2026-06" {
		t.Errorf("Game dict = %q/%q, want /srv/dict/2026-06", c.Game.DictDir, c.Game.DictVersion)
	}
	if c.Game.TimeoutSweepInterval != 30*time.Second {
		t.Errorf("Game.TimeoutSweepInterval = %s, want 30s", c.Game.TimeoutSweepInterval)
	}
	if c.Game.CacheTTL != time.Hour {
		t.Errorf("Game.CacheTTL = %s, want 1h", c.Game.CacheTTL)
	}
	if c.LogLevel != "debug" {
		t.Errorf("LogLevel = %q", c.LogLevel)
	}
	if c.Postgres.MaxOpenConns != 7 {
		t.Errorf("Postgres.MaxOpenConns = %d, want 7", c.Postgres.MaxOpenConns)
	}
	if c.Postgres.OperationTimeout != 3*time.Second {
		t.Errorf("Postgres.OperationTimeout = %s, want 3s", c.Postgres.OperationTimeout)
	}
	if c.Telemetry.ServiceName != "scrabble-test" {
		t.Errorf("Telemetry.ServiceName = %q", c.Telemetry.ServiceName)
	}
	if c.Telemetry.TracesExporter != telemetry.ExporterStdout {
		t.Errorf("Telemetry.TracesExporter = %q, want %q", c.Telemetry.TracesExporter, telemetry.ExporterStdout)
	}
}

// TestLoadRejectsMissingDSN verifies that an empty DSN fails validation.
func TestLoadRejectsMissingDSN(t *testing.T) {
	t.Setenv("BACKEND_POSTGRES_DSN", "")
	if _, err := Load(); err == nil {
		t.Fatal("Load: expected an error for a missing DSN, got nil")
	}
}

// TestLoadRejectsInvalidLevel verifies that an unknown log level is rejected.
func TestLoadRejectsInvalidLevel(t *testing.T) {
	t.Setenv("BACKEND_POSTGRES_DSN", testDSN)
	t.Setenv("BACKEND_LOG_LEVEL", "verbose")
	if _, err := Load(); err == nil {
		t.Fatal("Load: expected an error for an invalid log level, got nil")
	}
}

// TestLoadRejectsMissingDictDir verifies that an unset dictionary directory fails
// validation (the game subsystem cannot load without it).
func TestLoadRejectsMissingDictDir(t *testing.T) {
	t.Setenv("BACKEND_POSTGRES_DSN", testDSN)
	t.Setenv("BACKEND_LOG_LEVEL", "info")
	t.Setenv("BACKEND_DICT_DIR", "")
	if _, err := Load(); err == nil {
		t.Fatal("Load: expected an error for a missing dictionary dir, got nil")
	}
}

// TestLoadRejectsMalformedInt verifies that a non-numeric pool size is rejected.
func TestLoadRejectsMalformedInt(t *testing.T) {
	t.Setenv("BACKEND_POSTGRES_DSN", testDSN)
	t.Setenv("BACKEND_POSTGRES_MAX_OPEN_CONNS", "lots")
	if _, err := Load(); err == nil {
		t.Fatal("Load: expected an error for a malformed int, got nil")
	}
}

// TestLoadRejectsMalformedDuration verifies that a malformed duration is rejected.
func TestLoadRejectsMalformedDuration(t *testing.T) {
	t.Setenv("BACKEND_POSTGRES_DSN", testDSN)
	t.Setenv("BACKEND_POSTGRES_OPERATION_TIMEOUT", "soon")
	if _, err := Load(); err == nil {
		t.Fatal("Load: expected an error for a malformed duration, got nil")
	}
}

// TestLoadRejectsUnsupportedExporter verifies that an exporter outside the
// supported set is rejected.
func TestLoadRejectsUnsupportedExporter(t *testing.T) {
	t.Setenv("BACKEND_POSTGRES_DSN", testDSN)
	t.Setenv("BACKEND_OTEL_TRACES_EXPORTER", "prometheus")
	if _, err := Load(); err == nil {
		t.Fatal("Load: expected an error for an unsupported exporter, got nil")
	}
}

// TestLoadAcceptsOTLPExporter verifies that the otlp exporter is now accepted
// (the collector is stood up with the deploy; the default stays none).
func TestLoadAcceptsOTLPExporter(t *testing.T) {
	t.Setenv("BACKEND_POSTGRES_DSN", testDSN)
	t.Setenv("BACKEND_DICT_DIR", "/dict")
	t.Setenv("BACKEND_OTEL_TRACES_EXPORTER", "otlp")
	t.Setenv("BACKEND_OTEL_METRICS_EXPORTER", "otlp")
	if _, err := Load(); err != nil {
		t.Fatalf("Load with otlp exporters: %v", err)
	}
}

// TestLoadGuestReaperDefaultsAndOverride covers the guest-reaper knobs: defaults
// when unset, an override, and rejection of a non-positive value.
func TestLoadGuestReaperDefaultsAndOverride(t *testing.T) {
	t.Setenv("BACKEND_POSTGRES_DSN", testDSN)
	t.Setenv("BACKEND_DICT_DIR", "/dict")

	c, err := Load()
	if err != nil {
		t.Fatalf("Load: %v", err)
	}
	if c.GuestReapInterval != defaultGuestReapInterval {
		t.Errorf("GuestReapInterval = %s, want %s", c.GuestReapInterval, defaultGuestReapInterval)
	}
	if c.GuestRetention != defaultGuestRetention {
		t.Errorf("GuestRetention = %s, want %s", c.GuestRetention, defaultGuestRetention)
	}

	t.Setenv("BACKEND_GUEST_RETENTION", "168h")
	if c, err = Load(); err != nil {
		t.Fatalf("Load (override): %v", err)
	} else if c.GuestRetention != 168*time.Hour {
		t.Errorf("GuestRetention = %s, want 168h", c.GuestRetention)
	}

	t.Setenv("BACKEND_GUEST_REAP_INTERVAL", "0s")
	if _, err := Load(); err == nil {
		t.Fatal("Load: expected an error for a non-positive reap interval, got nil")
	}
}

// TestLoadMyNalogTimeZone pins the taxpayer's time zone: it defaults to Europe/Moscow and an
// unresolvable zone is a hard boot failure, never a quiet fall back to UTC.
//
// The offset a receipt carries decides which tax month an income is filed under, so a silent UTC
// default would misfile every near-midnight payment at a month boundary. That is also why the
// backend embeds the IANA database (a blank time/tzdata import in cmd/backend) instead of trusting
// the base image to ship one.
func TestLoadMyNalogTimeZone(t *testing.T) {
	base := func(t *testing.T) {
		t.Helper()
		t.Setenv("BACKEND_POSTGRES_DSN", testDSN)
		t.Setenv("BACKEND_DICT_DIR", "/dict")
	}

	t.Run("defaults to the taxpayer's zone", func(t *testing.T) {
		base(t)
		t.Setenv("BACKEND_MYNALOG_TZ", "")
		c, err := Load()
		if err != nil {
			t.Fatalf("load: %v", err)
		}
		if got := c.MyNalog.Location.String(); got != "Europe/Moscow" {
			t.Fatalf("time zone = %q, want Europe/Moscow", got)
		}
	})

	t.Run("honours an explicit zone", func(t *testing.T) {
		base(t)
		t.Setenv("BACKEND_MYNALOG_TZ", "Asia/Yekaterinburg")
		c, err := Load()
		if err != nil {
			t.Fatalf("load: %v", err)
		}
		if got := c.MyNalog.Location.String(); got != "Asia/Yekaterinburg" {
			t.Fatalf("time zone = %q", got)
		}
	})

	t.Run("refuses an unresolvable zone", func(t *testing.T) {
		base(t)
		t.Setenv("BACKEND_MYNALOG_TZ", "Mars/Olympus_Mons")
		if _, err := Load(); err == nil {
			t.Fatal("an unknown time zone must fail the boot, not fall back to UTC")
		}
	})
}
