package test

import (
	"fmt"
	"log"
	"os"
	"path"
	"path/filepath"
	"runtime"

	gitPkg "coopcloud.tech/abra/pkg/git"
	"git.coopcloud.tech/toolshed/godotenv"
)

var (
	AppName    = "test_app.example.com"
	StackName  = "test_app_example_com"
	ServerName = "test_server"
	RecipeName = "test_recipe"

	TFiles   = []string{"bar.env", "foo.env"}
	TFolders = []string{"dir1", "dir2"}

	ServerDir = os.ExpandEnv("$ABRA_DIR/servers/test_server")
	RecipeDir = os.ExpandEnv("$ABRA_DIR/recipes/test_recipe")
	TestDir   = os.ExpandEnv("$PWD/../../tests/resources/test_dir")

	AppEnvPath = path.Join(ServerDir, fmt.Sprintf("%s.env", AppName))

	AbraTestRecipe = "abra-test-recipe"
)

func Teardown() {
	abraDir := os.ExpandEnv("$ABRA_DIR")
	if abraDir == fmt.Sprintf("%s/.abra", os.ExpandEnv("$HOME")) {
		log.Fatal("set $ABRA_DIR before running the test suite")
	}

	if err := os.RemoveAll(abraDir); err != nil {
		log.Fatal(err)
	}
}

func Setup() {
	Teardown()

	if err := os.Mkdir(os.ExpandEnv("$ABRA_DIR"), 0764); err != nil {
		if !os.IsExist(err) {
			log.Fatal(err)
		}
	}

	if err := os.Mkdir(os.ExpandEnv("$ABRA_DIR/servers"), 0700); err != nil {
		if !os.IsExist(err) {
			log.Fatal(err)
		}
	}

	if err := os.Mkdir(os.ExpandEnv("$ABRA_DIR/recipes"), 0764); err != nil {
		if !os.IsExist(err) {
			log.Fatal(err)
		}
	}

	_, f, _, ok := runtime.Caller(0)
	if !ok {
		log.Fatal("Setup: unable to discover current working directory of file")
	}
	pwd := filepath.Dir(f)

	serverSrcDir := filepath.Join(pwd, "/../../tests/resources/test_server")
	serverDestDir := os.ExpandEnv("$ABRA_DIR/servers/test_server")
	if err := os.CopyFS(serverDestDir, os.DirFS(serverSrcDir)); err != nil {
		log.Fatal(err)
	}

	recipeSrcDir := filepath.Join(pwd, "/../../tests/resources/test_recipe")
	recipeDestDir := os.ExpandEnv("$ABRA_DIR/recipes/test_recipe")
	if err := os.CopyFS(recipeDestDir, os.DirFS(recipeSrcDir)); err != nil {
		log.Fatal(err)
	}

	if err := gitPkg.Init(recipeDestDir, true, "tester", "helo@coopcloud.tech"); err != nil {
		log.Fatal(err)
	}
}

func AddEnv(envKey, envValue string) error {
	filePath := os.ExpandEnv(fmt.Sprintf("$ABRA_DIR/servers/%s/%s.env", ServerName, AppName))

	envVars, _, err := godotenv.Read(filePath)
	if err != nil {
		return err
	}

	envVars[envKey] = envValue

	if err := godotenv.Write(envVars, filePath); err != nil {
		return err
	}

	return nil
}
