package divert

import (
	"os"
	"path/filepath"
	"runtime"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func TestInstallDriver_ExtractsAndVerifies(t *testing.T) {
	if runtime.GOOS != "windows" {
		t.Skip("Windows-only path")
	}
	tmp := t.TempDir()
	res, err := installDriverInto(tmp)
	require.NoError(t, err)
	assert.FileExists(t, filepath.Join(tmp, "WinDivert64.sys"))
	assert.FileExists(t, filepath.Join(tmp, "WinDivert.dll"))
	assert.Equal(t, filepath.Join(tmp, "WinDivert64.sys"), res.SysPath)
	assert.Equal(t, filepath.Join(tmp, "WinDivert.dll"), res.DllPath)
}

func TestInstallDriver_RefusesARM64(t *testing.T) {
	if runtime.GOARCH != "arm64" {
		t.Skip("only meaningful on arm64")
	}
	_, err := installDriverInto(t.TempDir())
	require.Error(t, err)
	assert.Contains(t, err.Error(), "ARM64")
}

func TestInstallDriver_DetectsTampering(t *testing.T) {
	if runtime.GOOS != "windows" {
		t.Skip()
	}
	tmp := t.TempDir()
	// Pre-populate the destination with garbage of the same name so the
	// installer's existing-file SHA-check fails and it overwrites.
	require.NoError(t, os.WriteFile(filepath.Join(tmp, "WinDivert64.sys"), []byte("garbage"), 0644))
	res, err := installDriverInto(tmp)
	require.NoError(t, err)
	// After install, the file should have the expected SHA, not garbage.
	assert.NotEmpty(t, res.SysPath)
	stat, err := os.Stat(res.SysPath)
	require.NoError(t, err)
	assert.Greater(t, stat.Size(), int64(1000))
}
