// Path: Backend/internal/config/config.go

package config

import (
	"os"
	"strings"
)

type Config struct {
	Port               string
	Environment        string
	AllowedOrigins     string
	DatabaseURL        string
	JWTSecret          string
	SessionCookie      string
	MockDataDir        string
	AdminReseedEnabled bool
	AdminReseedSecret  string
	ReseedPagePassword string
	AIReviewEndpoint   string
	AIReviewAPIKey     string
	AIReviewModel      string
}

func Load() *Config {
	return &Config{
		Port:               getEnv("BACKEND_INTERNAL_PORT", "8081"),
		Environment:        getEnv("GO_ENV", "development"),
		AllowedOrigins:     getEnv("ALLOWED_ORIGINS", "http://localhost:3000,http://localhost:4321,http://localhost:8080,http://windows-wsl:8080"),
		DatabaseURL:        getEnv("DATABASE_URL", "postgres://boostai:boostai_dev_password@localhost:5439/boostai?sslmode=disable"),
		JWTSecret:          getEnv("JWT_SECRET", "boostai-dev-jwt-secret-change-me"),
		SessionCookie:      getEnv("SESSION_COOKIE_NAME", "boostai_session"),
		MockDataDir:        getEnv("MOCK_DATA_DIR", "../Mock-Data"),
		AdminReseedEnabled: getEnvBool("ENABLE_ADMIN_RESEED", false),
		AdminReseedSecret:  getEnv("ADMIN_RESEED_SECRET", ""),
		ReseedPagePassword: getEnv("RESEED_PAGE_PASSWORD", "1588"),
		AIReviewEndpoint:   getEnv("AI_REVIEW_ENDPOINT", ""),
		AIReviewAPIKey:     getEnv("AI_REVIEW_API_KEY", ""),
		AIReviewModel:      getEnv("AI_REVIEW_MODEL", ""),
	}
}

func (c *Config) IsDevelopment() bool {
	return strings.ToLower(c.Environment) == "development"
}

func (c *Config) IsProduction() bool {
	return strings.ToLower(c.Environment) == "production"
}

func getEnv(key, fallback string) string {
	if value, exists := os.LookupEnv(key); exists {
		return value
	}

	return fallback
}

func getEnvBool(key string, fallback bool) bool {
	value, exists := os.LookupEnv(key)
	if !exists {
		return fallback
	}

	switch strings.TrimSpace(strings.ToLower(value)) {
	case "1", "true", "yes", "on":
		return true
	case "0", "false", "no", "off":
		return false
	default:
		return fallback
	}
}
