package handlers

import "testing"

func TestParseSemver(t *testing.T) {
	tests := []struct {
		input   string
		want    Semver
		wantErr bool
	}{
		{"1.2.3", Semver{1, 2, 3, ""}, false},
		{"v1.2.3", Semver{1, 2, 3, ""}, false},
		{"0.0.0", Semver{0, 0, 0, ""}, false},
		{"1.2.3-beta.1", Semver{1, 2, 3, "beta.1"}, false},
		{"v0.5.4-rc1", Semver{0, 5, 4, "rc1"}, false},
		{"10.20.30", Semver{10, 20, 30, ""}, false},
		{"", Semver{}, true},
		{"not-a-version", Semver{}, true},
		{"1.2", Semver{}, true},
		{"1.2.3.4", Semver{}, true},
		{"a.b.c", Semver{}, true},
	}

	for _, tt := range tests {
		t.Run(tt.input, func(t *testing.T) {
			got, err := ParseSemver(tt.input)
			if tt.wantErr {
				if err == nil {
					t.Fatalf("ParseSemver(%q) expected error, got %v", tt.input, got)
				}
				return
			}
			if err != nil {
				t.Fatalf("ParseSemver(%q) unexpected error: %v", tt.input, err)
			}
			if got != tt.want {
				t.Errorf("ParseSemver(%q) = %v, want %v", tt.input, got, tt.want)
			}
		})
	}
}

func TestSemverCompare(t *testing.T) {
	tests := []struct {
		a, b string
		want int
	}{
		{"1.0.0", "2.0.0", -1},
		{"2.0.0", "1.0.0", 1},
		{"1.1.0", "1.0.0", 1},
		{"1.0.0", "1.1.0", -1},
		{"1.0.1", "1.0.0", 1},
		{"1.0.0", "1.0.0", 0},
		{"1.0.0-alpha", "1.0.0", -1},
		{"1.0.0", "1.0.0-alpha", 1},
		{"1.0.0-alpha", "1.0.0-beta", -1},
		{"1.0.0-beta", "1.0.0-alpha", 1},
		{"1.0.0-alpha", "1.0.0-alpha", 0},
		{"0.5.3", "0.5.4", -1},
		{"0.5.4", "0.5.3", 1},
	}

	for _, tt := range tests {
		t.Run(tt.a+"_vs_"+tt.b, func(t *testing.T) {
			a, _ := ParseSemver(tt.a)
			b, _ := ParseSemver(tt.b)
			got := a.Compare(b)
			if got != tt.want {
				t.Errorf("(%s).Compare(%s) = %d, want %d", tt.a, tt.b, got, tt.want)
			}
		})
	}
}

func TestSemverString(t *testing.T) {
	tests := []struct {
		v    Semver
		want string
	}{
		{Semver{1, 2, 3, ""}, "1.2.3"},
		{Semver{0, 0, 0, ""}, "0.0.0"},
		{Semver{1, 0, 0, "beta.1"}, "1.0.0-beta.1"},
	}

	for _, tt := range tests {
		t.Run(tt.want, func(t *testing.T) {
			if got := tt.v.String(); got != tt.want {
				t.Errorf("Semver.String() = %q, want %q", got, tt.want)
			}
		})
	}
}
