package scaling_test

import (
	"encoding/json"
	"math/rand"
	"os"
	"os/exec"
	"testing"
	"time"

	pusherConfig "code.cloudfoundry.org/cf-pusher/config"
	"github.com/cloudfoundry/cf-test-helpers/v2/cf"
	helpers "github.com/cloudfoundry/cf-test-helpers/v2/config"
	. "github.com/onsi/ginkgo/v2"
	. "github.com/onsi/gomega"
	"github.com/onsi/gomega/gexec"
)

const Timeout_Short = 20 * time.Second

var (
	config          *helpers.Config
	pushConfig      pusherConfig.Config
	randomGenerator *rand.Rand
)

func TestScaling(t *testing.T) {
	randomGenerator = rand.New(rand.NewSource(GinkgoRandomSeed() + int64(GinkgoParallelProcess())))

	RegisterFailHandler(Fail)
	RunSpecs(t, "Scaling Suite")
}

var _ = BeforeSuite(func() {
	config = helpers.LoadConfig()

	configPath := helpers.ConfigPath()
	configBytes, err := os.ReadFile(configPath)
	Expect(err).NotTo(HaveOccurred())

	err = json.Unmarshal(configBytes, &pushConfig)
	Expect(err).NotTo(HaveOccurred())

	if pushConfig.Applications <= 0 {
		Fail("Applications count needs to be greater than 0")
	}

	if pushConfig.AppInstances <= 0 {
		Fail("AppInstances count needs to be greater than 0")
	}

	if pushConfig.ProxyApplications <= 0 {
		Fail("ProxyApplications count needs to be greater than 0")
	}

	if pushConfig.ProxyInstances <= 0 {
		Fail("ProxyInstances count needs to be greater than 0")
	}

	Expect(cf.Cf("api", "--skip-ssl-validation", config.ApiEndpoint).Wait(Timeout_Short)).To(gexec.Exit(0))
	AuthAsAdmin()
	Expect(cf.Cf("target", "-o", pushConfig.Prefix+"org", "-s", pushConfig.Prefix+"space").Wait(Timeout_Short)).To(gexec.Exit(0))
})

func AuthAsAdmin() {
	Auth(config.AdminUser, config.AdminPassword)
}

func Auth(username, password string) {
	By("authenticating as " + username)
	cmd := exec.Command("cf", "auth", username, password)
	sess, err := gexec.Start(cmd, nil, nil)
	Expect(err).NotTo(HaveOccurred())
	Eventually(sess.Wait(Timeout_Short)).Should(gexec.Exit(0))
}
