package service

import (
	"fmt"
	"os"
	"strings"
)

func parseBoolEnv(v string) (bool, bool) {
	s := strings.ToLower(strings.TrimSpace(v))
	switch s {
	case "1", "true", "yes", "on", "enabled":
		return true, true
	case "0", "false", "no", "off", "disabled":
		return false, true
	default:
		return false, false
	}
}

func envNameOrDefault() string {
	for _, key := range []string{"APP_ENV", "AISUPPORT_ENV", "ENV", "GO_ENV"} {
		if v := strings.TrimSpace(os.Getenv(key)); v != "" {
			return strings.ToLower(v)
		}
	}
	return ""
}

func IsAuth0Enabled() bool {
	if enabled, ok := parseBoolEnv(os.Getenv("AUTH0_ENABLED")); ok {
		return enabled
	}

	// Secure by default: authentication is ON unless explicitly disabled via
	// AUTH0_ENABLED=false. We intentionally do NOT infer this from the
	// environment name. Disabling auth based on a string like "dev" is a footgun:
	// a misnamed or unconfigured environment would silently fall into bypass mode
	// and trust the plaintext X-User-Email header (i.e. effectively no auth).
	return true
}

// isRecognizedDevEnv reports whether APP_ENV (or its fallbacks) names a
// local/dev/test environment where the auth bypass is acceptable.
func isRecognizedDevEnv() bool {
	switch envNameOrDefault() {
	case "dev", "development", "local", "test", "testing", "":
		return true
	default:
		return false
	}
}

// AssertSafeAuthConfig fails closed at startup. If the auth bypass is enabled
// (Auth0 disabled or DEV_BYPASS_AUTH=true) in anything other than a recognized
// dev/test environment, it returns an error so the process refuses to boot
// rather than run effectively unauthenticated.
func AssertSafeAuthConfig() error {
	if !ShouldBypassAuth() {
		return nil
	}
	if isRecognizedDevEnv() {
		return nil
	}
	return fmt.Errorf(
		"refusing to start: auth bypass is enabled (AUTH0_ENABLED=false or DEV_BYPASS_AUTH=true) "+
			"but APP_ENV=%q is not a recognized dev/test environment; "+
			"set AUTH0_ENABLED=true to enforce authentication",
		envNameOrDefault(),
	)
}

func IsDevBypassEnabled() bool {
	if enabled, ok := parseBoolEnv(os.Getenv("DEV_BYPASS_AUTH")); ok {
		return enabled
	}
	return false
}

func ShouldBypassAuth() bool {
	return !IsAuth0Enabled() || IsDevBypassEnabled()
}

func BypassUserEmail() string {
	return strings.ToLower(strings.TrimSpace(os.Getenv("DEV_BYPASS_USER_EMAIL")))
}
