// Package config provides service-specific configuration.
package config

import (
	"os"
	"strings"

	"{{GO_MODULE}}/pkg/config"
)

// Config extends the base config with {{COMPONENT_NAME}}-specific settings.
type Config struct {
	config.AppConfig
	Server   config.ServerConfig
	Database config.DatabaseConfig
	Logging  config.LoggingConfig

	// Auth
	AuthEnabled         bool
	JWTSecret           string
	RegistrationEnabled bool

	// Redis for cross-process SSE event delivery
	RedisURL string

	// Notify service for email delivery (OTP, magic links, password reset, etc.)
	// When NotifyURL is empty, emails are logged to stdout (dev mode).
	NotifyURL    string
	NotifyAPIKey string
	NotifyHost   string
	NotifyFrom   string

	// Email branding — injected into every transactional email.
	AppName      string // APP_NAME, default: "{{COMPONENT_NAME}}"
	AppURL       string // APP_URL, default: ""
	SupportEmail string // SUPPORT_EMAIL, default: NOTIFY_FROM value
	LogoURL      string // LOGO_URL, default: "" (hides logo area)
	BrandColor   string // BRAND_COLOR, default: "#6366f1"

	// Dev mode seed user — seeded into the in-memory user store on startup so the
	// developer's email is always available without re-registering after each restart.
	// No effect when DATABASE_URL is set (production uses real persistence).
	DevUserEmail    string // DEV_USER_EMAIL, e.g. "you@example.com"
	DevUserPassword string // DEV_USER_PASSWORD, default: "DevPassword1"
}

// Load reads configuration from environment variables.
func Load() *Config {
	regEnabled := true
	if v := os.Getenv("REGISTRATION_ENABLED"); v != "" {
		regEnabled = strings.EqualFold(v, "true")
	}

	notifyFrom := getEnvDefault("NOTIFY_FROM", "noreply@{{PROJECT_NAME}}.com")

	cfg := &Config{
		AppConfig: config.ReadAppConfig(),
		Server:    config.ReadServerConfig(),
		Database:  config.ReadDatabaseConfig(),
		Logging:   config.ReadLoggingConfig(),

		AuthEnabled:         strings.EqualFold(os.Getenv("AUTH_ENABLED"), "true"),
		JWTSecret:           os.Getenv("JWT_SECRET"),
		RegistrationEnabled: regEnabled,
		RedisURL:            os.Getenv("REDIS_URL"),

		NotifyURL:    os.Getenv("NOTIFY_URL"),
		NotifyAPIKey: os.Getenv("NOTIFY_API_KEY"),
		NotifyHost:   os.Getenv("NOTIFY_HOST"),
		NotifyFrom:   notifyFrom,

		AppName:      getEnvDefault("APP_NAME", "{{COMPONENT_NAME}}"),
		AppURL:       os.Getenv("APP_URL"),
		SupportEmail: getEnvDefault("SUPPORT_EMAIL", notifyFrom),
		LogoURL:      os.Getenv("LOGO_URL"),
		BrandColor:   getEnvDefault("BRAND_COLOR", "#6366f1"),

		DevUserEmail:    os.Getenv("DEV_USER_EMAIL"),
		DevUserPassword: getEnvDefault("DEV_USER_PASSWORD", "DevPassword1"),
	}

	return cfg
}

func getEnvDefault(key, defaultVal string) string {
	if v := os.Getenv(key); v != "" {
		return v
	}
	return defaultVal
}
