package config

import (
	"fmt"
	"sort"
)

// EnvVarDoc représente la documentation d'une variable d'environnement (T0033)
type EnvVarDoc struct {
	Name        string
	Type        string
	Required    bool
	Default     string
	Description string
	Example     string
}

// envVarsDocs contient la documentation de toutes les variables d'environnement (T0033)
var envVarsDocs = map[string]EnvVarDoc{
	"APP_ENV": {
		Name:        "APP_ENV",
		Type:        "string",
		Required:    false,
		Default:     "development",
		Description: "Environment mode (development, production, test)",
		Example:     "production",
	},
	"APP_PORT": {
		Name:        "APP_PORT",
		Type:        "int",
		Required:    false,
		Default:     "8080",
		Description: "Port for HTTP server (1-65535)",
		Example:     "8080",
	},
	"JWT_SECRET": {
		Name:        "JWT_SECRET",
		Type:        "string",
		Required:    true,
		Default:     "",
		Description: "Secret key for JWT token signing and validation (minimum 32 characters)",
		Example:     "your-super-secret-jwt-key-minimum-32-characters-long",
	},
	"DATABASE_URL": {
		Name:        "DATABASE_URL",
		Type:        "string",
		Required:    false,
		Default:     "postgresql://veza:password@localhost:5432/veza_db",
		Description: "PostgreSQL database connection URL (must start with postgres://, postgresql://, or sqlite://)",
		Example:     "postgresql://user:password@localhost:5432/veza_db",
	},
	"DB_HOST": {
		Name:        "DB_HOST",
		Type:        "string",
		Required:    false,
		Default:     "localhost",
		Description: "Database host address",
		Example:     "localhost",
	},
	"DB_PORT": {
		Name:        "DB_PORT",
		Type:        "int",
		Required:    false,
		Default:     "5432",
		Description: "Database port number",
		Example:     "5432",
	},
	"DB_USER": {
		Name:        "DB_USER",
		Type:        "string",
		Required:    false,
		Default:     "veza",
		Description: "Database username",
		Example:     "veza",
	},
	"DB_PASSWORD": {
		Name:        "DB_PASSWORD",
		Type:        "string",
		Required:    true,
		Default:     "",
		Description: "Database password (required)",
		Example:     "your-secure-database-password",
	},
	"DB_NAME": {
		Name:        "DB_NAME",
		Type:        "string",
		Required:    false,
		Default:     "veza_db",
		Description: "Database name",
		Example:     "veza_db",
	},
	"REDIS_URL": {
		Name:        "REDIS_URL",
		Type:        "string",
		Required:    false,
		Default:     "redis://localhost:6379",
		Description: "Redis connection URL (must start with redis:// or rediss://)",
		Example:     "redis://localhost:6379",
	},
	"CORS_ALLOWED_ORIGINS": {
		Name:        "CORS_ALLOWED_ORIGINS",
		Type:        "string",
		Required:    false,
		Default:     "*",
		Description: "Comma-separated list of allowed CORS origins (use * for all origins)",
		Example:     "http://localhost:3000,https://app.veza.com",
	},
	"RATE_LIMIT_LIMIT": {
		Name:        "RATE_LIMIT_LIMIT",
		Type:        "int",
		Required:    false,
		Default:     "100",
		Description: "Maximum number of requests allowed per time window for rate limiting",
		Example:     "100",
	},
	"RATE_LIMIT_WINDOW": {
		Name:        "RATE_LIMIT_WINDOW",
		Type:        "int",
		Required:    false,
		Default:     "60",
		Description: "Time window in seconds for rate limiting",
		Example:     "60",
	},
	"LOG_LEVEL": {
		Name:        "LOG_LEVEL",
		Type:        "string",
		Required:    false,
		Default:     "INFO",
		Description: "Logging level (DEBUG, INFO, WARN, ERROR)",
		Example:     "INFO",
	},
}

// GenerateConfigDocs génère la documentation markdown pour toutes les variables d'environnement (T0033)
func GenerateConfigDocs() string {
	var keys []string
	for k := range envVarsDocs {
		keys = append(keys, k)
	}
	sort.Strings(keys)

	md := "# Configuration Variables\n\n"
	md += "This document lists all environment variables used by the Veza backend API.\n\n"
	md += "## Overview\n\n"
	md += "Variables can be set in:\n"
	md += "- System environment variables (highest priority)\n"
	md += "- `.env.{APP_ENV}` file (e.g., `.env.development`, `.env.production`)\n"
	md += "- `.env` file (fallback)\n\n"
	md += "---\n\n"

	for _, key := range keys {
		doc := envVarsDocs[key]
		md += fmt.Sprintf("## %s\n\n", doc.Name)

		md += fmt.Sprintf("**Type**: `%s`\n\n", doc.Type)

		if doc.Required {
			md += "**Required**: ✅ Yes\n\n"
		} else {
			md += "**Required**: ❌ No\n\n"
		}

		if doc.Default != "" {
			md += fmt.Sprintf("**Default**: `%s`\n\n", doc.Default)
		}

		md += fmt.Sprintf("**Description**: %s\n\n", doc.Description)

		if doc.Example != "" {
			md += fmt.Sprintf("**Example**:\n```bash\nexport %s=%s\n```\n\n", doc.Name, doc.Example)
		}

		md += "---\n\n"
	}

	return md
}

// GetAllEnvVarDocs retourne la map complète de documentation (utile pour les tests et l'introspection)
func GetAllEnvVarDocs() map[string]EnvVarDoc {
	// Retourner une copie pour éviter les modifications externes
	result := make(map[string]EnvVarDoc)
	for k, v := range envVarsDocs {
		result[k] = v
	}
	return result
}
