package Users_test

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"testing"

	"git.tovijaeschke.xyz/tovi/Capsule/Backend/Models"
	"git.tovijaeschke.xyz/tovi/Capsule/Backend/Tests"
)

func Test_SearchUsers(t *testing.T) {
	client, ts, err := Tests.InitTestEnv()
	if err != nil {
		t.Errorf("Expected nil, recieved %s", err.Error())
		return
	}

	u2, err := Tests.InitTestCreateUser("abcd")

	req, _ := http.NewRequest(
		"GET",
		fmt.Sprintf("%s/api/v1/auth/users?username=%s", ts.URL, u2.Username),
		nil,
	)

	resp, err := client.Do(req)
	if err != nil {
		t.Errorf("Expected nil, recieved %s", err.Error())
		return
	}

	if resp.StatusCode != http.StatusOK {
		t.Errorf("Expected %d, recieved %d", http.StatusOK, resp.StatusCode)
		return
	}

	requestBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		t.Errorf("Expected %d, recieved %d", http.StatusOK, resp.StatusCode)
		return
	}

	var user Models.User

	json.Unmarshal(requestBody, &user)

	if user.Username != "abcd" {
		t.Errorf("Expected abcd, recieved %s", user.Username)
		return
	}

	if user.Password != "" {
		t.Errorf("Expected \"\", recieved %s", user.Password)
		return
	}

	if user.AsymmetricPrivateKey != "" {
		t.Errorf("Expected \"\", recieved %s", user.AsymmetricPrivateKey)
		return
	}
}

func Test_SearchUsersPartialMatchFails(t *testing.T) {
	client, ts, err := Tests.InitTestEnv()
	if err != nil {
		t.Errorf("Expected nil, recieved %s", err.Error())
		return
	}

	_, err = Tests.InitTestCreateUser("abcd")

	req, _ := http.NewRequest(
		"GET",
		fmt.Sprintf("%s/api/v1/auth/users?username=%s", ts.URL, "abc"),
		nil,
	)

	resp, err := client.Do(req)
	if err != nil {
		t.Errorf("Expected nil, recieved %s", err.Error())
		return
	}

	if resp.StatusCode != http.StatusNotFound {
		t.Errorf("Expected %d, recieved %d", http.StatusOK, resp.StatusCode)
		return
	}

	requestBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		t.Errorf("Expected %d, recieved %d", http.StatusOK, resp.StatusCode)
		return
	}

	var user interface{}

	json.Unmarshal(requestBody, &user)

	if user != nil {
		t.Errorf("Expected nil, recieved %+v", user)
		return
	}
}
