package main

import (
	"github.com/stretchr/testify/assert"
	"github.com/vishvananda/netlink"
	"net/http"
	"net/http/httptest"
	"testing"
)

func TestWireguardIsSetUp(t *testing.T) {
	setupWireguard()

	deviceFound := checkForNetworkDevice("wgSampleServer", t)
	assert.True(t, deviceFound, "device should exists")

	down()

	deviceFound = checkForNetworkDevice("wgSampleServer", t)
	assert.False(t, deviceFound, "device should not exists")
}

func TestHTTPAPIReturnOKBasicRoute(t *testing.T) {
	setupHTTPServer()
	req, _ := http.NewRequest("GET", "/", nil)
	resp := executeRequest(req)
	if resp.Body.String() != "ok" {
		t.Errorf("Basic route should return ok")
	}
}

func executeRequest(req *http.Request) *httptest.ResponseRecorder {
	rr := httptest.NewRecorder()
	mux.ServeHTTP(rr, req)

	return rr
}

func checkForNetworkDevice(name string, t *testing.T) bool {
	res, err := netlink.LinkList()

	assert.Nil(t, err, "shouldn't return an error return devices")

	foundDevice := false
	for _, device := range res {
		if device.Attrs().Name == name {
			foundDevice = true
		}
	}

	return foundDevice
}