package httpmanifest

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

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

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

	server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
		if request.Header.Get("Authorization") != "Bearer token" {
			http.Error(writer, "unauthorized", http.StatusUnauthorized)
			return
		}
		_, _ = writer.Write([]byte(`{
			"schemaVersion": 1,
			"productID": "com.example.app",
			"releases": [
				{
					"id": "1.1.0",
					"version": "1.1.0",
					"channel": "stable",
					"publishedAt": "2026-03-01T03:10:56Z",
					"artifacts": [
						{"os": "darwin", "arch": "arm64", "kind": "bundle-archive", "format": "zip", "url": "https://example.invalid/1.1.0.zip", "sha256": "111"}
					]
				},
				{
					"id": "1.2.0",
					"version": "1.2.0",
					"channel": "stable",
					"publishedAt": "2026-03-02T03:10:56Z",
					"artifacts": [
						{"os": "darwin", "arch": "arm64", "kind": "bundle-archive", "format": "zip", "url": "https://example.invalid/1.2.0.zip", "sha256": "222"}
					]
				}
			]
		}`))
	}))
	defer server.Close()

	provider, err := New(Config{
		ManifestURL: server.URL,
		PrepareRequest: func(request *http.Request) error {
			request.Header.Set("Authorization", "Bearer token")
			return nil
		},
	})
	if err != nil {
		t.Fatalf("New returned error: %v", err)
	}

	release, err := provider.Resolve(context.Background(), updates.ResolveRequest{
		App: updates.AppDescriptor{
			ProductID:      "com.example.app",
			CurrentVersion: "1.0.0",
			Channel:        updates.ChannelStable,
			OS:             "darwin",
			Arch:           "arm64",
		},
	})
	if err != nil {
		t.Fatalf("Resolve returned error: %v", err)
	}
	if release == nil || release.Version != "1.2.0" {
		t.Fatalf("Resolve selected %+v", release)
	}
}
