package githubreleases

import (
	"context"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/Eriyc/rules_wails/pkg/wails3kit/updates"
)

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

	serverURL := ""
	server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
		switch request.URL.Path {
		case "/repos/owner/repo/releases":
			_, _ = writer.Write([]byte(`[
				{
					"tag_name": "v1.2.0",
					"body": "notes",
					"prerelease": false,
					"published_at": "2026-03-01T03:10:56Z",
					"assets": [
						{"name": "com.example.app_1.2.0_linux_amd64.zip", "browser_download_url": "` + serverURL + `/artifact.zip"},
						{"name": "com.example.app_1.2.0_linux_amd64.zip.sha256", "browser_download_url": "` + serverURL + `/artifact.zip.sha256"}
					]
				}
			]`))
		case "/artifact.zip.sha256":
			_, _ = writer.Write([]byte("abcdef artifact.zip"))
		default:
			http.NotFound(writer, request)
		}
	}))
	defer server.Close()
	serverURL = server.URL

	provider, err := New(Config{
		Owner:      "owner",
		Repo:       "repo",
		HTTPClient: server.Client(),
	})
	if err != nil {
		t.Fatalf("New returned error: %v", err)
	}

	provider.baseURL = server.URL

	release, err := provider.Resolve(context.Background(), updates.ResolveRequest{
		App: updates.AppDescriptor{
			ProductID:      "com.example.app",
			CurrentVersion: "1.0.0",
			Channel:        updates.ChannelStable,
			OS:             "linux",
			Arch:           "amd64",
		},
	})
	if err != nil {
		t.Fatalf("Resolve returned error: %v", err)
	}
	if release == nil {
		t.Fatal("Resolve returned nil release")
	}
	if release.Artifact.URL != server.URL+"/artifact.zip" {
		t.Fatalf("unexpected artifact url: %s", release.Artifact.URL)
	}
	if release.Artifact.SHA256 != "abcdef" {
		t.Fatalf("unexpected checksum: %s", release.Artifact.SHA256)
	}
}
