package runtimeenv

import (
	"os"
	"testing"
)

func TestParseMode(t *testing.T) {
	t.Parallel()

	tests := []struct {
		in   string
		want Mode
		ok   bool
	}{
		{in: "", want: ModeAuto, ok: true},
		{in: "auto", want: ModeAuto, ok: true},
		{in: "local", want: ModeLocal, ok: true},
		{in: "livecd", want: ModeLiveCD, ok: true},
		{in: "bad", ok: false},
	}

	for _, test := range tests {
		got, err := ParseMode(test.in)
		if test.ok && err != nil {
			t.Fatalf("ParseMode(%q): %v", test.in, err)
		}
		if !test.ok && err == nil {
			t.Fatalf("ParseMode(%q): expected error", test.in)
		}
		if test.ok && got != test.want {
			t.Fatalf("ParseMode(%q): got %q want %q", test.in, got, test.want)
		}
	}
}

func TestDetectHonorsFlag(t *testing.T) {
	t.Parallel()

	info, err := Detect("livecd")
	if err != nil {
		t.Fatalf("Detect(flag): %v", err)
	}
	if info.Mode != ModeLiveCD || info.Reason != "flag" {
		t.Fatalf("unexpected info: %+v", info)
	}
}

func TestDetectHonorsEnv(t *testing.T) {
	t.Parallel()

	old := os.Getenv("BEE_RUNTIME")
	t.Cleanup(func() {
		_ = os.Setenv("BEE_RUNTIME", old)
	})
	if err := os.Setenv("BEE_RUNTIME", "local"); err != nil {
		t.Fatalf("Setenv: %v", err)
	}

	info, err := Detect("auto")
	if err != nil {
		t.Fatalf("Detect(env): %v", err)
	}
	if info.Mode != ModeLocal || info.Reason != "env:BEE_RUNTIME" {
		t.Fatalf("unexpected info: %+v", info)
	}
}
