package config_test // intentionally use a different package than config to ensure we're testing the package lookup correctly

import (
	"flag"
	"os"
	"testing"

	"code.justin.tv/common/config"
)

func resetForTesting() {
	flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ContinueOnError)
	flag.Usage = nil
}

func TestDefault(t *testing.T) {
	resetForTesting()

	config.Register(map[string]string{
		"test-flag": "my default",
	})

	config.Parse()

	val := config.Resolve("test-flag")
	if val != "my default" {
		t.Fatalf("unexpected val: %v", val)
	}
}

func TestEnvOverride(t *testing.T) {
	resetForTesting()

	config.Register(map[string]string{
		"test-flag": "my default",
	})

	os.Setenv("TEST_FLAG", "new thing")

	config.Parse()

	val := config.Resolve("test-flag")
	if val != "new thing" {
		t.Fatalf("unexpected val: %v", val)
	}
}

func TestResolveUnknownFlag(t *testing.T) {
	resetForTesting()

	config.Register(map[string]string{})
	config.Parse()

	val := config.Resolve("unknown-flag")
	if val != "" {
		t.Fatalf("unexpected val: %v", val)
	}
}

func TestMustResolveValidFlag(t *testing.T) {
	resetForTesting()

	config.Register(map[string]string{
		"valid-flag": "red white and blue",
	})
	config.Parse()

	val := config.MustResolve("valid-flag")
	if val != "red white and blue" {
		t.Fatalf("unexpected val: %v", val)
	}
}

func TestMustResolveInvalidFlag(t *testing.T) {
	resetForTesting()

	config.Register(map[string]string{})
	config.Parse()

	defer func() {
		if err := recover(); err == nil {
			t.Fatalf("MustResolve did not panic as expected")
		}
	}()
	config.MustResolve("missing-flag")
}
