package main

import (
	"log"
	"os"
	"time"

	"go.uber.org/zap"
	"veza-backend-api/internal/database"
)

func main() {
	logger, _ := zap.NewProduction()

	// Override config from env
	// Override config from env
	var cfg *database.Config

	if dbURL := os.Getenv("DATABASE_URL"); dbURL != "" {
		cfg = &database.Config{
			URL:           dbURL,
			MaxRetries:    5,
			RetryInterval: 2 * time.Second,
		}
	} else {
		// SECURITY: DB_PASSWORD is required - no default value to prevent security issues
		dbPassword := getEnvRequired("DB_PASSWORD")
		cfg = &database.Config{
			Host:          getEnv("DB_HOST", "localhost"),
			Port:          getEnv("DB_PORT", "5432"),
			Username:      getEnv("DB_USER", "veza"),
			Password:      dbPassword,
			Database:      getEnv("DB_NAME", "veza"),
			SSLMode:       "disable",
			MaxRetries:    5,
			RetryInterval: 2 * time.Second,
		}
	}

	db, err := database.NewDatabaseWithRetry(cfg, logger)
	if err != nil {
		log.Fatalf("Failed to connect: %v", err)
	}
	defer db.Close()

	if err := db.RunMigrations(); err != nil {
		log.Fatalf("Migration failed: %v", err)
	}

	logger.Info("Migrations completed successfully")
}

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

// getEnvRequired récupère une variable d'environnement requise (panique si absente)
func getEnvRequired(key string) string {
	value := os.Getenv(key)
	if value == "" {
		log.Fatalf("FATAL: Required environment variable %s is not set", key)
	}
	return value
}
