package config

import (
	"testing"
	"time"
)

// TestDefaults asserts the BUILT-IN defaults, so every variable it checks has
// to be explicitly cleared first.
//
// It used to call Load() against the ambient environment, which meant it read
// the real .env — APP_ENV=development, FIX_PAYDEBT_REFERENCE=false,
// CORS_ORIGINS=* — and then asserted the hardcoded defaults. It could therefore
// only ever pass on a machine with no .env at all, and on every machine that has
// one it failed for a reason that had nothing to do with defaults. A test that
// is guaranteed to fail in every real environment is worse than no test: it
// trains you to ignore a red suite, which is exactly how the tier-config work
// alongside it went unnoticed.
//
// t.Setenv (not os.Setenv) so each variable is restored when the test ends and
// cannot leak into anything running after it.
func TestDefaults(t *testing.T) {
	for _, k := range []string{
		"APP_ENV",
		"APP_PORT",
		"TOKEN_TTL_HOURS",
		"ALLOW_NEGATIVE_STOCK",
		// Spelled exactly as config.go reads it. The old failure message said
		// FIX_PAY_DEBT_REFERENCE with an underscore, which is a name nothing
		// reads — the code, .env and .env.example all use FIX_PAYDEBT_REFERENCE.
		// Unsetting the wrong spelling would have left the override in place and
		// the assertion would still fail, for the original reason.
		"FIX_PAYDEBT_REFERENCE",
		"IDEMPOTENCY_TTL_HOURS",
		"CORS_ORIGINS",
		"TZ",
		"TIMEZONE",
	} {
		t.Setenv(k, "")
	}

	c := Load()
	if c.AppEnv != "local" {
		t.Errorf("AppEnv default = %q, want local", c.AppEnv)
	}
	if c.AppPort != 8080 {
		t.Errorf("AppPort default = %d, want 8080", c.AppPort)
	}
	if c.TokenTTLHours != 24 {
		t.Errorf("TokenTTLHours default = %d, want 24", c.TokenTTLHours)
	}
	if !c.AllowNegativeStock {
		t.Error("AllowNegativeStock default = false, want true")
	}
	if c.FixPayDebtReference != true {
		t.Errorf("FixPayDebtReference default = %v, want true", c.FixPayDebtReference)
	}
	if c.IdempotencyTTLHours != 24 {
		t.Errorf("IdempotencyTTLHours default = %d, want 24", c.IdempotencyTTLHours)
	}
	if len(c.CORSOrigins) != 1 || c.CORSOrigins[0] != "http://localhost:3000" {
		t.Errorf("CORSOrigins default = %v", c.CORSOrigins)
	}
	if c.Timezone().String() != "Asia/Jakarta" {
		t.Errorf("Timezone default = %q, want Asia/Jakarta", c.Timezone())
	}
}

func TestTimezoneFallback(t *testing.T) {
	c := Config{timezone: "Not/AZone"}
	if c.Timezone() != time.UTC {
		t.Errorf("invalid timezone should fall back to UTC, got %v", c.Timezone())
	}
}
