package main

import (
	"fmt"
	"log"
	"os"
	"path/filepath"
	"system-altrak/internal/config"

	"gorm.io/gorm"
)

func ApplyIndexesSQL(db *gorm.DB, cfg *config.Config) error {
	if db == nil {
		return fmt.Errorf("database connection is nil")
	}
	if cfg == nil {
		return fmt.Errorf("config is nil")
	}

	log.Println("🔧 Starting index creation...")

	// Read SQL file with resilient path resolution
	sqlFile := resolveSQLFilePath()
	sqlContent, err := os.ReadFile(sqlFile)
	if err != nil {
		return fmt.Errorf("failed to read SQL file (%s): %w", sqlFile, err)
	}

	// Execute SQL
	if err := db.Exec(string(sqlContent)).Error; err != nil {
		return fmt.Errorf("failed to execute SQL: %w", err)
	}

	log.Println("✅ All indexes created successfully!")

	// Verify indexes
	var count int
	switch cfg.DBType {
	case "mysql":
		err = db.Raw("SELECT COUNT(*) FROM information_schema.statistics WHERE table_schema = DATABASE()").Scan(&count).Error
	case "sqlite":
		err = db.Raw("SELECT COUNT(*) FROM sqlite_master WHERE type = 'index'").Scan(&count).Error
	default:
		err = fmt.Errorf("unsupported database type for index verification: %s", cfg.DBType)
	}
	if err != nil {
		log.Printf("⚠️  Could not verify indexes: %v", err)
	} else {
		fmt.Printf("📊 Total indexes in database: %d\n", count)
	}

	log.Println("🎉 Index migration completed!")
	return nil
}

func resolveSQLFilePath() string {
	candidates := []string{
		filepath.Join("database", "sql", "add_indexes.sql"),
		filepath.Join("..", "..", "database", "sql", "add_indexes.sql"),
	}

	for _, p := range candidates {
		if _, err := os.Stat(p); err == nil {
			return p
		}
	}

	return candidates[0]
}
