package runner

import (
	"context"
	"path/filepath"
	"testing"

	"gitlab.com/Timfa/bluegit/internal/access"
	"gitlab.com/Timfa/bluegit/internal/store"
)

func TestEnvironmentExpand(t *testing.T) {
	s, err := store.Open(filepath.Join(t.TempDir(), "b.db"), make([]byte, 32))
	if err != nil {
		t.Fatal(err)
	}
	defer s.Close()
	ctx := context.Background()
	tim, _ := s.UpsertUser(ctx, 1, "tim", "", false)
	g, _ := s.CreateGroup(ctx, tim.ID, "Team", "team", "", access.RoleReadonly)
	repo, _ := s.CreateRepo(ctx, "group", g.ID, "app", "", "master", "private")
	put := func(kind string, id int64, n, v string, on bool) {
		if err := s.PutSecret(ctx, kind, id, n, v, false); err != nil {
			t.Fatal(err)
		}
		_ = s.SetSecretExpand(ctx, kind, id, n, on)
	}
	put("group", g.ID, "HOST", "db.local", false)
	put("group", g.ID, "URL", "http://$HOST/$CI_PROJECT_NAME", true)
	put("group", g.ID, "OVR", "grp-$HOST", true)
	put("repo", repo.ID, "OVR", "repo-$HOST", false) // project wint, ook vlag uit
	put("repo", repo.ID, "PASS", "pa$$w$HOST", false)
	put("repo", repo.ID, "LIT", "$$x-${NOPE}", true)
	put("repo", repo.ID, "JOBV", "s-$HOST", true)
	r := &Runner{Store: s}
	job := store.Job{Name: "t", Variables: map[string]string{"JOBV": "job-$HOST"}}
	env, mask, err := r.environment(ctx, repo, store.Pipeline{Ref: "feature"}, job, "")
	if err != nil {
		t.Fatal(err)
	}
	want := map[string]string{
		"URL": "http://db.local/app", "OVR": "repo-$HOST", "PASS": "pa$$w$HOST",
		"LIT": "$x-${NOPE}", "JOBV": "job-$HOST",
	}
	for k, v := range want {
		if env[k] != v {
			t.Errorf("%s=%q want %q", k, env[k], v)
		}
	}
	found := false
	for _, m := range mask {
		found = found || m == "http://db.local/app"
	}
	if !found {
		t.Error("uitgebreide waarde niet gemaskeerd")
	}
}
