package config

import (
	"flag"
	"os"
	"testing"
)

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

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

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

	Parse()

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

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

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

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

	Parse()

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

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

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

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

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

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

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

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

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

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