package registry

import (
	"log/slog"
	"testing"

	"github.com/google/go-cmp/cmp"
)

const proxyName = "aqua-proxy"

func TestPackageInfo_overrideVersion(t *testing.T) {
	t.Parallel()
	data := []struct {
		title   string
		pkgInfo *PackageInfo
		child   *VersionOverride
		exp     *PackageInfo
	}{
		{
			title: "normal",
			pkgInfo: &PackageInfo{
				Type:        PkgInfoTypeGitHubRelease,
				RepoOwner:   "abiosoft",
				RepoName:    repoNameColima,
				Description: "Docker (and Kubernetes) on MacOS with minimal setup",
				Asset:       "colima-amd64",
				Files: []*File{
					{
						Name: proxyName,
					},
				},
			},
			child: &VersionOverride{
				Type: PkgInfoTypeGitHubContent,
				Path: repoNameColima,
			},
			exp: &PackageInfo{
				Type:        PkgInfoTypeGitHubContent,
				RepoOwner:   "abiosoft",
				RepoName:    repoNameColima,
				Description: "Docker (and Kubernetes) on MacOS with minimal setup",
				Files: []*File{
					{
						Name: proxyName,
					},
				},
				Path: repoNameColima,
			},
		},
	}
	for _, d := range data {
		t.Run(d.title, func(t *testing.T) {
			t.Parallel()
			pkgInfo := d.pkgInfo.overrideVersion(d.child)
			if diff := cmp.Diff(d.exp, pkgInfo); diff != "" {
				t.Fatal(diff)
			}
		})
	}
}

func TestPackageInfo_setVersion(t *testing.T) { //nolint:funlen
	t.Parallel()
	data := []struct {
		title   string
		version string
		pkgInfo *PackageInfo
		exp     *PackageInfo
	}{
		{
			title: "no version constraint",
			exp: &PackageInfo{
				Type: PkgInfoTypeGitHubContent,
				Path: pkgFoo,
			},
			pkgInfo: &PackageInfo{
				Type: PkgInfoTypeGitHubContent,
				Path: pkgFoo,
			},
		},
		{
			title: "version constraint",
			exp: &PackageInfo{
				Type:               PkgInfoTypeGitHubContent,
				Path:               pkgFoo,
				VersionConstraints: semverGTE040,
			},
			pkgInfo: &PackageInfo{
				Type:               PkgInfoTypeGitHubContent,
				Path:               pkgFoo,
				VersionConstraints: semverGTE040,
			},
			version: "v0.5.0",
		},
		{
			title: "child version constraint",
			exp: &PackageInfo{
				Type:               PkgInfoTypeGitHubContent,
				Path:               pkgBar,
				VersionConstraints: semverGTE040,
				VersionOverrides: []*VersionOverride{
					{
						VersionConstraints: `semver("< 0.4.0")`,
						Path:               pkgBar,
					},
				},
			},
			pkgInfo: &PackageInfo{
				Type:               PkgInfoTypeGitHubContent,
				Path:               pkgFoo,
				VersionConstraints: semverGTE040,
				VersionOverrides: []*VersionOverride{
					{
						VersionConstraints: `semver("< 0.4.0")`,
						Path:               pkgBar,
					},
				},
			},
			version: "v0.3.0",
		},
	}
	logger := slog.New(slog.DiscardHandler)
	for _, d := range data {
		t.Run(d.title, func(t *testing.T) {
			t.Parallel()
			pkgInfo, err := d.pkgInfo.SetVersion(logger, d.version)
			if err != nil {
				t.Fatal(err)
			}
			if diff := cmp.Diff(pkgInfo, d.exp); diff != "" {
				t.Fatal(diff)
			}
		})
	}
}
