package main

import (
	"net/http/httptest"
	"os"
	"path/filepath"
	"runtime"
	"testing"

	"github.com/Eriyc/rules_wails/examples/wails3_init_updater/mockupdateserver"
	"github.com/Eriyc/rules_wails/pkg/wails3kit/updates"
	updateswails "github.com/Eriyc/rules_wails/pkg/wails3kit/updates/wails"
)

func TestNewControllerAndService(t *testing.T) {
	server := httptest.NewServer(mockupdateserver.NewHandler())
	defer server.Close()

	t.Setenv("UPDATER_MANIFEST_URL", server.URL+"/manifest.json")
	t.Setenv("UPDATER_TOKEN", mockupdateserver.BearerToken)

	executablePath := filepath.Join(t.TempDir(), entryPointName())
	if err := os.WriteFile(executablePath, []byte("#!/bin/sh\nexit 0\n"), 0o755); err != nil {
		t.Fatalf("WriteFile returned error: %v", err)
	}

	controller, err := newController(testDescriptor(t, executablePath))
	if err != nil {
		t.Fatalf("newController returned error: %v", err)
	}

	service := NewUpdateService(updateswails.NewService(updateswails.Options{
		Controller: controller,
	}))
	if service.Snapshot().CurrentVersion != currentVersion {
		t.Fatalf("unexpected current version: %s", service.Snapshot().CurrentVersion)
	}
}

func testDescriptor(t *testing.T, executablePath string) updates.AppDescriptor {
	t.Helper()
	return updates.AppDescriptor{
		ProductID:        productID,
		CurrentVersion:   currentVersion,
		Channel:          updates.ChannelStable,
		OS:               runtime.GOOS,
		Arch:             runtime.GOARCH,
		ExecutablePath:   executablePath,
		WorkingDirectory: t.TempDir(),
	}
}

func entryPointName() string {
	if runtime.GOOS == "windows" {
		return "updater-example.exe"
	}
	return "updater-example"
}
