package envexpand

import "testing"

func TestExpandMap(t *testing.T) {
	vars := map[string]string{
		"POSTGRES_PASSWORD": "s3cret",
		"POSTGRES_USER":     "ulti",
		"POSTGRES_DB":       "ultidb",
		"ULTID_DB_URL":      "postgres://{{POSTGRES_USER}}:{{POSTGRES_PASSWORD}}@postgres:5432/{{POSTGRES_DB}}?sslmode=disable",
		"RUSTFS_SECRET_KEY": "key123",
		"NC_S3_SECRET":      "{{RUSTFS_SECRET_KEY}}",
	}

	out, err := ExpandMap(vars)
	if err != nil {
		t.Fatal(err)
	}

	want := "postgres://ulti:s3cret@postgres:5432/ultidb?sslmode=disable"
	if out["ULTID_DB_URL"] != want {
		t.Fatalf("ULTID_DB_URL = %q, want %q", out["ULTID_DB_URL"], want)
	}
	if out["NC_S3_SECRET"] != "key123" {
		t.Fatalf("NC_S3_SECRET = %q", out["NC_S3_SECRET"])
	}
}

func TestExpandMap_nested(t *testing.T) {
	vars := map[string]string{
		"A": "1",
		"B": "{{A}}2",
		"C": "x{{B}}y",
	}

	out, err := ExpandMap(vars)
	if err != nil {
		t.Fatal(err)
	}
	if out["C"] != "x12y" {
		t.Fatalf("C = %q", out["C"])
	}
}

func TestExpandMap_cycle(t *testing.T) {
	vars := map[string]string{
		"A": "{{B}}",
		"B": "{{A}}",
	}

	_, err := ExpandMap(vars)
	if err == nil {
		t.Fatal("expected cycle error")
	}
}

func TestParseLines(t *testing.T) {
	lines := []string{
		"# comment",
		"",
		`FOO=bar`,
		`QUOTED="hello"`,
	}
	vars, err := ParseLines(lines)
	if err != nil {
		t.Fatal(err)
	}
	if vars["FOO"] != "bar" || vars["QUOTED"] != "hello" {
		t.Fatalf("vars = %#v", vars)
	}
}
