package config_test

import (
	"fmt"
	"reflect"
	"testing"

	"coopcloud.tech/abra/pkg/config"
	"coopcloud.tech/abra/pkg/recipe"
	"github.com/stretchr/testify/assert"
)

func TestNewApp(t *testing.T) {
	app, err := config.NewApp(ExpectedAppEnv, AppName, ExpectedAppFile)
	if err != nil {
		t.Fatal(err)
	}
	if !reflect.DeepEqual(app, ExpectedApp) {
		t.Fatalf("did not get expected app type. Expected: %s; Got: %s", app, ExpectedApp)
	}
}

func TestReadAppEnvFile(t *testing.T) {
	app, err := config.ReadAppEnvFile(ExpectedAppFile, AppName)
	if err != nil {
		t.Fatal(err)
	}
	if !reflect.DeepEqual(app, ExpectedApp) {
		t.Fatalf("did not get expected app type. Expected: %s; Got: %s", app, ExpectedApp)
	}
}

func TestGetApp(t *testing.T) {
	app, err := config.GetApp(ExpectedAppFiles, AppName)
	if err != nil {
		t.Fatal(err)
	}
	if !reflect.DeepEqual(app, ExpectedApp) {
		t.Fatalf("did not get expected app type. Expected: %s; Got: %s", app, ExpectedApp)
	}
}

func TestGetComposeFiles(t *testing.T) {
	offline := true
	r, err := recipe.Get("abra-test-recipe", offline)
	if err != nil {
		t.Fatal(err)
	}

	tests := []struct {
		appEnv       map[string]string
		composeFiles []string
	}{
		{
			map[string]string{},
			[]string{
				fmt.Sprintf("%s/%s/compose.yml", config.RECIPES_DIR, r.Name),
			},
		},
		{
			map[string]string{"COMPOSE_FILE": "compose.yml"},
			[]string{
				fmt.Sprintf("%s/%s/compose.yml", config.RECIPES_DIR, r.Name),
			},
		},
		{
			map[string]string{"COMPOSE_FILE": "compose.extra_secret.yml"},
			[]string{
				fmt.Sprintf("%s/%s/compose.extra_secret.yml", config.RECIPES_DIR, r.Name),
			},
		},
		{
			map[string]string{"COMPOSE_FILE": "compose.yml:compose.extra_secret.yml"},
			[]string{
				fmt.Sprintf("%s/%s/compose.yml", config.RECIPES_DIR, r.Name),
				fmt.Sprintf("%s/%s/compose.extra_secret.yml", config.RECIPES_DIR, r.Name),
			},
		},
	}

	for _, test := range tests {
		composeFiles, err := config.GetComposeFiles(r.Name, test.appEnv)
		if err != nil {
			t.Fatal(err)
		}
		assert.Equal(t, composeFiles, test.composeFiles)
	}
}

func TestGetComposeFilesError(t *testing.T) {
	offline := true
	r, err := recipe.Get("abra-test-recipe", offline)
	if err != nil {
		t.Fatal(err)
	}

	tests := []struct{ appEnv map[string]string }{
		{map[string]string{"COMPOSE_FILE": "compose.yml::compose.foo.yml"}},
		{map[string]string{"COMPOSE_FILE": "doesnt.exist.yml"}},
	}

	for _, test := range tests {
		_, err := config.GetComposeFiles(r.Name, test.appEnv)
		if err == nil {
			t.Fatalf("should have failed: %v", test.appEnv)
		}
	}
}