package commands

import (
	"os"
	"os/exec"

	"github.com/contiamo/dev/cli/config"
	"github.com/spf13/cobra"
)

func init() {
	testCmd.Flags().String("repo", "eu.gcr.io/dev-and-test-env/contiamo-e2e", "e2e test docker image repo")
	testCmd.Flags().String("tag", "latest", "e2e test docker image tag")
}

var testCmd = &cobra.Command{
	Use:   "test",
	Short: "run the end-to-end test in the current localdev environment",
	Example: `
	Most of the time you want to use this:
		localdev test

	Use a specific test image:
		localdev test --tag=v1.1.0
	`,
	RunE: func(cmd *cobra.Command, args []string) error {
		repo, err := cmd.Flags().GetString("repo")
		if err != nil {
			return err
		}

		tag, err := cmd.Flags().GetString("tag")
		if err != nil {
			return err
		}

		image := repo + ":" + tag
		tester := exec.CommandContext(
			cmd.Context(),
			"docker",
			"run",
			"--net", "dev_default",
			"-e", "BASE_URL=http://nginx",
			"-e", "FOODMARTDB_HOST=postgresql-foodmart",
			image,
			"datahub-e2e",
		)
		tester.Dir = config.LocaldevRoot()
		tester.Stderr = cmd.OutOrStderr()
		tester.Stdout = cmd.OutOrStdout()
		tester.Env = os.Environ()

		return tester.Run()
	},
}
