package release

import (
	"strings"
	"testing"
)

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

	current := MustParseVersion(t, "1.0.0")
	options := BuildCommandOptions(Config{
		AllowedChannels:  []string{"alpha", "beta"},
		ReleaseStepsJSON: `[{"kind":"writeFile","path":"VERSION.txt","text":"$FULL_VERSION\n"}]`,
		PostVersion:      "echo post",
		Execution: ExecutionOptions{
			Commit: true,
			Tag:    true,
			Push:   true,
		},
	}, current)

	want := map[string]string{
		"release patch":      "1.0.1",
		"release minor":      "1.1.0",
		"release major":      "2.0.0",
		"release alpha":      "1.0.1-alpha.1",
		"release minor beta": "1.1.0-beta.1",
	}

	for command, nextVersion := range want {
		option, ok := findOptionByCommand(options, command)
		if !ok {
			t.Fatalf("expected command %q in options", command)
		}
		if option.NextVersion.String() != nextVersion {
			t.Fatalf("%s next version = %q, want %q", command, option.NextVersion.String(), nextVersion)
		}
		if !strings.Contains(option.Preview, "Release steps: yes") {
			t.Fatalf("%s preview missing release steps marker:\n%s", command, option.Preview)
		}
		if !strings.Contains(option.Preview, "Post-version:  yes") {
			t.Fatalf("%s preview missing post-version marker:\n%s", command, option.Preview)
		}
		if !strings.Contains(option.Preview, "git push:      yes") {
			t.Fatalf("%s preview missing git push marker:\n%s", command, option.Preview)
		}
	}
}

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

	current := MustParseVersion(t, "1.2.3-beta.2")
	options := BuildCommandOptions(Config{
		AllowedChannels: []string{"alpha", "beta", "rc"},
	}, current)

	stableOption, ok := findOptionByCommand(options, "release stable")
	if !ok {
		t.Fatalf("expected release stable option")
	}
	if stableOption.NextVersion.String() != "1.2.3" {
		t.Fatalf("release stable next version = %q, want 1.2.3", stableOption.NextVersion.String())
	}

	betaOption, ok := findOptionByCommand(options, "release beta")
	if !ok {
		t.Fatalf("expected release beta option")
	}
	if betaOption.NextVersion.String() != "1.2.3-beta.3" {
		t.Fatalf("release beta next version = %q, want 1.2.3-beta.3", betaOption.NextVersion.String())
	}

	patchOption, ok := findOptionByCommand(options, "release patch")
	if !ok {
		t.Fatalf("expected release patch option")
	}
	if patchOption.NextVersion.String() != "1.2.4-beta.1" {
		t.Fatalf("release patch next version = %q, want 1.2.4-beta.1", patchOption.NextVersion.String())
	}
}

func findOptionByCommand(options []CommandOption, command string) (CommandOption, bool) {
	for _, option := range options {
		if option.Command == command {
			return option, true
		}
	}
	return CommandOption{}, false
}
