package main

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

	"customer-support-system/internal/database"
	"customer-support-system/pkg/config"
	"customer-support-system/pkg/logger"
)

func main() {
	// Load configuration
	if err := config.LoadConfig(); err != nil {
		log.Fatalf("Failed to load configuration: %v", err)
	}

	// Initialize logger
	logger.InitLogger()

	// Connect to database
	if err := database.Connect(); err != nil {
		logger.WithError(err).Fatal("Failed to connect to database")
	}

	// Parse command line arguments
	action := flag.String("action", "up", "Migration action (up or down)")
	flag.Parse()

	// Run migrations based on action
	switch *action {
	case "up":
		if err := database.AutoMigrate(); err != nil {
			logger.WithError(err).Fatal("Failed to run database migrations")
		}
		fmt.Println("Database migrations completed successfully")
	case "down":
		// Note: GORM doesn't support automatic rollback of migrations
		// In a real application, you would need to implement a more sophisticated migration system
		fmt.Println("Automatic rollback is not supported with GORM")
		fmt.Println("Please manually revert the database schema changes")
	default:
		fmt.Printf("Unknown action: %s\n", *action)
		fmt.Println("Usage: go run cmd/migrate.go -action=[up|down]")
		os.Exit(1)
	}

	// Close database connection
	if err := database.Close(); err != nil {
		logger.WithError(err).Error("Failed to close database connection")
	}
}
