package config

// |@@| C

import (
	"context"
	erro "gardening/src/lib/error"
	"gardening/src/lib/operating_system"
	"os"
	"path/filepath"
	"runtime"
)

type Config struct {
	Data struct {
		RootDir string
	}
	OperatingSystemInterface operating_system.OperatingSystemInterface
}

func (this *Config) GetRootDir() string {
	if this.Data.RootDir != "" {
		return this.Data.RootDir
	}
	value, has := this.OperatingSystemInterface.LookupEnv(context.Background(), "ROOT_DIR")
	if has {
		return value
	}

	_, path, _, _ := runtime.Caller(0)
	path = filepath.Dir(path)
	rootDir := path + "/../../.."
	rootDir, _ = filepath.Abs(rootDir)
	return rootDir
}

func (this *Config) GetDataDir() string {
	return this.GetRootDir() + "/data"
}

func (this *Config) GetDbPath() string {
	return this.GetRootDir() + "/data/db.db"
}

func (this *Config) GetAuditLogsPath() string {
	return this.GetRootDir() + "/tmp/audit_logs.txt"
}

func (this *Config) IsDevOrTestEnv() bool {
	return os.Getenv("ENV") == "dev" || os.Getenv("ENV") == "test"
}

func (this *Config) IsDevEnv() bool {
	return os.Getenv("ENV") == "dev"
}

func (this *Config) IsEnv(name string) bool {
	return os.Getenv("ENV") == name
}

func (this *Config) GetEnvValue(ctx context.Context, key string) string {
	return this.OperatingSystemInterface.Getenv(ctx, key)
}

func (this *Config) HasEnvValue(ctx context.Context, key string) bool {
	_, has := this.OperatingSystemInterface.LookupEnv(ctx, key)
	if has {
		return true
	}
	return false
}

func (this *Config) MustGetEnvValue(ctx context.Context, key string) string {
	if !this.HasEnvValue(ctx, key) {
		panic(erro.N("env variable key not exist").KV("key", key))
	}
	return this.OperatingSystemInterface.Getenv(ctx, key)
}
