package main

import (
	"flag"
	"fmt"
	"log"
	"os"

	"github.com/timetracker/backend/internal/config"
	"github.com/timetracker/backend/internal/db"
	"github.com/timetracker/backend/internal/models"
	"gorm.io/gorm/logger"
)

func main() {
	// Parse command line flags
	verbose := false
	dropDB := flag.Bool("drop_db", false, "Drop the database before migrating")
	createDB := flag.Bool("create_db", false, "Create the database if it doesn't exist")

	flag.Parse()

	for _, arg := range os.Args[1:] {
		if arg == "--verbose" || arg == "-v" {
			verbose = true
		}
	}

	if verbose {
		fmt.Println("Running in verbose mode")
	}

	// Get database configuration with sensible defaults
	dbConfig := config.DefaultDatabaseConfig()

	// Override with environment variables if provided
	if host := os.Getenv("DB_HOST"); host != "" {
		dbConfig.Host = host
	}
	if port := os.Getenv("DB_PORT"); port != "" {
		var portInt int
		if _, err := fmt.Sscanf(port, "%d", &portInt); err == nil && portInt > 0 {
			dbConfig.Port = portInt
		}
	}
	if user := os.Getenv("DB_USER"); user != "" {
		dbConfig.User = user
	}
	if password := os.Getenv("DB_PASSWORD"); password != "" {
		dbConfig.Password = password
	}
	if dbName := os.Getenv("DB_NAME"); dbName != "" {
		dbConfig.DBName = dbName
	}
	if sslMode := os.Getenv("DB_SSLMODE"); sslMode != "" {
		dbConfig.SSLMode = sslMode
	}

	// Set log level
	dbConfig.LogLevel = logger.Info

	// Initialize database
	fmt.Println("Connecting to database...")

	var err error

	gormDB, err := db.GetGormDB(dbConfig, "postgres")
	if err != nil {
		log.Fatalf("Error getting gorm DB: %v", err)
	}
	sqlDB, err := gormDB.DB()
	if err != nil {
		log.Fatalf("Error getting sql DB: %v", err)
	}

	if *dropDB {
		fmt.Printf("Dropping database %s...\n", dbConfig.DBName)
		_, err = sqlDB.Exec(fmt.Sprintf("DROP DATABASE IF EXISTS %s", dbConfig.DBName))
		if err != nil {
			log.Fatalf("Error dropping database %s: %v", dbConfig.DBName, err)
		}
		fmt.Printf("✓ Database %s dropped successfully\n", dbConfig.DBName)
	}

	if *createDB {
		fmt.Printf("Creating database %s...\n", dbConfig.DBName)
		_, err = sqlDB.Exec(fmt.Sprintf("CREATE DATABASE %s", dbConfig.DBName))
		if err != nil {
			log.Fatalf("Error creating database %s: %v", dbConfig.DBName, err)
		}
		fmt.Printf("✓ Database %s created successfully\n", dbConfig.DBName)
	}

	if err = db.InitDB(dbConfig); err != nil {
		log.Fatalf("Error initializing database: %v", err)
	}
	defer func() {
		if err := db.CloseDB(); err != nil {
			log.Printf("Error closing database connection: %v", err)
		}
	}()
	fmt.Println("✓ Database connection successful")

	// Run migrations
	fmt.Println("Running database migrations...")
	if err = models.MigrateDB(); err != nil {
		log.Fatalf("Error migrating database: %v", err)
	}
	fmt.Println("✓ Database migrations completed successfully")
}
