// +build e2e

package e2e

import (
	"net/http"
	"net/http/httptest"

	"code.justin.tv/beefcake/server/internal/beefcakeserver"
	"code.justin.tv/beefcake/server/internal/client"
	"code.justin.tv/beefcake/server/rpc/beefcake"
	"code.justin.tv/sse/malachai/pkg/s2s/caller"
)

type e2eTest struct {
	environment string

	clients  *client.Loader
	server   *httptest.Server
	Client   *http.Client
	Beefcake beefcake.Beefcake
}

func (mt *e2eTest) Setup() (err error) {
	if mt.clients, err = mt.newClientLoader(); err != nil {
		return err
	}

	if err := mt.createServer(); err != nil {
		return err
	}

	s2sRoundTripper, err := mt.s2sRoundTripper()
	if err != nil {
		return err
	}

	mt.Client = &http.Client{
		Transport: s2sRoundTripper,
	}
	mt.Beefcake = beefcake.NewBeefcakeProtobufClient(mt.URL(), mt.Client)

	return nil
}

func (mt *e2eTest) newClientLoader() (*client.Loader, error) {
	clients, err := client.EnvironmentLoader(mt.environment)
	if err != nil {
		return nil, err
	}

	clients = clients.WithCustomSessionRole(
		clients.Config().TaskServiceRoleArn.Get())
	return clients, nil
}

func (mt *e2eTest) s2sRoundTripper() (*caller.RoundTripper, error) {
	return caller.NewRoundTripper(
		mt.clients.Config().IntegrationS2SServiceName.Get(),
		&caller.Config{},
		mt.clients.Logger())
}

func (mt *e2eTest) createServer() error {
	handler, err := beefcakeserver.New(mt.clients)
	if err != nil {
		return err
	}

	mt.server = httptest.NewServer(handler)
	return nil
}

func (mt e2eTest) Path(path string) string {
	return mt.server.URL + path
}

func (mt e2eTest) URL() string {
	return mt.server.URL
}

func (mt e2eTest) CleanUp() {
	mt.server.Close()
}
