//go:build integration

package integrationtest

import (
	"os"
	"strconv"
	"strings"
)

// Env holds integration test configuration from ULTI_TEST_* variables.
type Env struct {
	Enabled       bool
	DBURL         string
	RedisAddr     string
	S3Endpoint    string
	S3AccessKey   string
	S3SecretKey   string
	S3UseSSL      bool
	AutoMigrate   bool
	Parallel      int
	Nextcloud     bool
	NextcloudURL  string
	Immich        bool
	ImmichURL     string
	Jitsi         bool
	Meilisearch   bool
	MeilisearchURL string
	MeilisearchKey string
}

func LoadEnv() Env {
	return Env{
		Enabled:        envTruthy("ULTI_TEST_INTEGRATION"),
		DBURL:          strings.TrimSpace(os.Getenv("ULTI_TEST_DB_URL")),
		RedisAddr:      strings.TrimSpace(os.Getenv("ULTI_TEST_REDIS_ADDR")),
		S3Endpoint:     strings.TrimSpace(os.Getenv("ULTI_TEST_S3_ENDPOINT")),
		S3AccessKey:    envOr("ULTI_TEST_S3_ACCESS_KEY", "ultiadmin"),
		S3SecretKey:    envOr("ULTI_TEST_S3_SECRET_KEY", "changeme123"),
		S3UseSSL:       envTruthy("ULTI_TEST_S3_USE_SSL"),
		AutoMigrate:    !envFalsy("ULTI_TEST_AUTO_MIGRATE"),
		Parallel:       envInt("ULTI_TEST_PARALLEL", 4),
		Nextcloud:      envTruthy("ULTI_TEST_NEXTCLOUD"),
		NextcloudURL:   strings.TrimSpace(os.Getenv("ULTI_TEST_NEXTCLOUD_URL")),
		Immich:         envTruthy("ULTI_TEST_IMMICH"),
		ImmichURL:      strings.TrimSpace(os.Getenv("ULTI_TEST_IMMICH_URL")),
		Jitsi:          envTruthy("ULTI_TEST_JITSI"),
		Meilisearch:    envTruthy("ULTI_TEST_MEILISEARCH"),
		MeilisearchURL: strings.TrimSpace(os.Getenv("ULTI_TEST_MEILISEARCH_URL")),
		MeilisearchKey: strings.TrimSpace(os.Getenv("ULTI_TEST_MEILISEARCH_KEY")),
	}
}

func envOr(key, fallback string) string {
	if v := strings.TrimSpace(os.Getenv(key)); v != "" {
		return v
	}
	return fallback
}

func envTruthy(key string) bool {
	v := strings.ToLower(strings.TrimSpace(os.Getenv(key)))
	return v == "1" || v == "true" || v == "yes"
}

func envFalsy(key string) bool {
	v := strings.ToLower(strings.TrimSpace(os.Getenv(key)))
	return v == "0" || v == "false" || v == "no"
}

func envInt(key string, fallback int) int {
	v := strings.TrimSpace(os.Getenv(key))
	if v == "" {
		return fallback
	}
	n, err := strconv.Atoi(v)
	if err != nil {
		return fallback
	}
	return n
}
