package mongodb

import (
	"context"
	"fmt"
	toxiproxy "github.com/Shopify/toxiproxy/v2/client"
	"testing"
)

func initToxiProxy(t *testing.T) *toxiproxy.Proxy {

	client := toxiproxy.NewClient("localhost:8474")
	proxy, err := client.CreateProxy("mongo", "localhost:0", "localhost:27017")
	if err != nil {
		t.Error(err)
	}
	return proxy
}

func TestTrainingStorage_FindTrainings_latency(t *testing.T) {

	//given
	proxy := initToxiProxy(t)
	defer proxy.Delete()

	proxy.AddToxic("mongo", "latency", "", 1, toxiproxy.Attributes{
		"latency": 100,
	})

	config := Config{Url: "mongodb://" + proxy.Listen, Username: "admin", Passwort: "admin"}
	storage := NewTrainingStorage(config)

	//when
	trainings, err := storage.FindTrainings(context.Background())

	//then
	if err != nil {
		t.Error(err)
		return
	}

	if len(trainings) != 0 {
		t.Error("expected empty result but got ", trainings)
	}
}

func TestTrainingStorage_FindTrainings_slow_close(t *testing.T) {

	//given
	proxy := initToxiProxy(t)
	defer proxy.Delete()

	_, err := proxy.AddToxic("mongo", "slow_close", "", 1, toxiproxy.Attributes{
		"delay": 1000,
	})
	if err != nil {
		t.Error(err)
		return
	}

	config := Config{Url: "mongodb://" + proxy.Listen, Username: "admin", Passwort: "admin"}
	storage := NewTrainingStorage(config)

	//when
	trainings, err := storage.FindTrainings(context.Background())

	//then
	if err != nil {
		t.Error(err)
		return
	}

	if len(trainings) != 0 {
		t.Error("expected empty result but got ", trainings)
	}

}

func TestTrainingStorage_FindTrainings_reset_peer(t *testing.T) {

	//given
	proxy := initToxiProxy(t)
	defer proxy.Delete()

	_, err := proxy.AddToxic("mongo", "reset_peer", "", 1, toxiproxy.Attributes{
		"timeout": 30000,
	})
	if err != nil {
		t.Error(err)
		return
	}

	config := Config{Url: "mongodb://" + proxy.Listen, Username: "admin", Passwort: "admin"}
	storage := NewTrainingStorage(config)

	//when
	_, err = storage.FindTrainings(context.Background())

	//then
	if err == nil {
		t.Error("expected timeout but got none")
		return
	}

	fmt.Println(err)

}
